Ashvini Ashvini - 1 year ago 55
Python Question

python create dictionary from list of strings and list of integers

I need urgent help.Please someone help me.

I have two lists: one contain the name of pages like ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']

and the other list contain the corresponding page number like [1, 2, 3]

I want to create a dictionary from two lists such that the splitted words from list one as a key and corresponding value from list two as value. And if key already is in dictionary then append value to it.

For the above example I want a dictionary like:

'Barrel': [1],
'-': [1],
'Part': [1],
'1': [1],
'Petit': [2],
'Trees': [2],
# '(sketch)': [2],
'Island': [3],
'(sketch)':[2, 3] #in this line the value appended as the key already has a value 2


Answer Source

You might be surprised that the results are out of order, but that's because dicts in python don't have an order. If you want them ordered you'll need to use something other than a vanilla dict.

titles =  ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
pages =  [1, 2, 3]

finalDict = {}
for title, page in zip(titles, pages):
    for word in title.split(" "):
        if word not in finalDict.keys():
            finalDict[word] = [int(page)]
            finalDict[word] += [int(page)]


This outputs:

{'Part': [1], '1': [1], 'Trees': [2], 'Island': [3], 'Barrel': [1], '-': [1], '(sketch)': [2, 3], 'Petit': [2]}