I have a list

x = ['abc','1','2','3','def','6','8','5','13','mcg','568','35469','6453']

I want the output file in a dictionary as follows:

dict = {'abc':['1','2','3'],'def':['6','8','5','13'],'mcg':['568','35469','6453']}

How can i do this?

For example like this. It is made more complicated the thing that you want to keep the integers as strings, so we can not append directly the int value:

x = ['abc','1','2','3','def','6','8','5','13','mcg','568','35469','6453']
key = x[0]
mydict = dict()

for data in x:
    try:
        # prove if int fails
        # we could append here, but we do not want to convert to int
        int(data)
    except ValueError:
        # if fails it is string key
        key = data
    else:
        # else it is numeric string,
        # append as numeric string without conversion to int
        # like requested, default value empty list
        mydict[key] = mydict.get(key,[])+[data]

print mydict

omg. this is great! Thank you very much. But i have another question. How will the output be if there are words in place of numbers and vice versa.

Only need to exchange lines 12 and 17 as long as they are not mixed (not values and keys both numbers).

tats awesome! Thank a lot! You are my python god! :)

Now i got another doubt! Please help me with this too!

I have 2 dictionaries. dict and dict1.
All i have to do is, for each key in dict1,
I should take its value and go to dict. The values are keys in dict. If the keys in dict have a common value(s), i should output it into a new dictionary.

This is the code i have written so far.

>>> test=[]
>>> dict={'a':['100','101','190','76'],'b':['100','176','154','76'],'c':['190','45'],'d':['101','190'],'e':['100']}
>>> dict1={'1':['a','b'],'2':['c','d']}
>>> for x in dict1:
...     for y in dict1[x]:
...             if y in dict:
...                     test.append(dict[y])
...
>>> test
[['100', '101', '190'], ['100', '176', '154', '76'], ['190', '45'], ['101', '190']]

My output should be,

dict3={'1':['100','76'],'2':['190']}

You are making list, but your wish is to make dictionary. Check your program logic! Put print inside loop for debug. Do not use dict as variable name.

Yup. ur right. this is what i am getting now.

>>> dict1={'a':['100','101','190','76'],'b':['100','176','154','76'],'c':['190','45'],'d':['101','190'],'e':['100']}
>>> dict2={'1':['a','b'],'2':['c','d']}
>>> dict3={}
>>> for x in dict2:
...     for y in dict2[x]:
...             if y in dict1:
...                     dict3[x]=dict[y]
...
>>> dict3
{'1': ['100', '176', '154', '76'], '2': ['101', '190']}

Can u please correct this code???

In case of your example this works (asume two long lists for dict2):

dict1={'a':['100','101','190','76'],'b':['100','176','154','76'],'c':['190','45'],'d':['101','190'],'e':['100']}
dict2={'1':['a','b'],'2':['c','d']}
dict3 = {}
for x in dict2:
    key1, key2 = dict2[x]
    dict3[x] = list(set(dict1[key1]) & set(dict1[key2]))
             
print dict3

From this we can see that correct data structure for values would be set, not list.

right! what if in dict2 the key '2' has

and in dict1 the key 'e' has

ie.,

dict1={'a':['100','101','190','76'],'b':['100','176','154','76'],'c':['190','45'],'d':['101','190'],'e':['100','190']}
dict2={'1':['a','b'],'2':['c','d','e']}
dict3 = {}
for x in dict2:
    if len(dict2[x])==2:
        key1, key2 = dict2[x]
        dict3[x] = list(set(dict1[key1]) & set(dict1[key2]))
    elif len(dict2[x])==3:
        key1, key2, key3 = dict2[x]
        dict3[x] = list(set(dict1[key1]) & set(dict1[key2]) & set(dict1[key3])
print dict3

this will be fine. but what if len(dict2[x]) varies each time...
can the number of lines be reduced?

Maybe something like this is efficient enough, I change numbers to real numbers and data structure to set (to avoid doubles)

dict1={'a':['100','101','190','76'],'b':['100','176','154','76'],'c':['190','45'],'d':['101','190'],'e':['100']}
dict2={'1':['a','b'],'2':['c','d']}
## looks from other post that you are not necessary happy with string numbers
dict3 = dict((int(x), sorted(set(
        [int(value)
         for a in dict2[x]
         for value in dict1[a]
         if all(value in dict1[v]
                for v in dict2[x])]
        )))  for x in dict2)
             
print dict3
commented: This is great!!! It gives me more interest to learn the language!!! Thank you very much for your kindness!! :) :) +1

For example like this. It is made more complicated the thing that you want to keep the integers as strings, so we can not append directly the int value:

Neater way if you like numbers to be really numbers:

x = ['abc','1','2','3','def','6','8','5','13','mcg','568','35469','6453']
key = x[0]
mydict = dict()

for data in x:
    try:
        # prove if int fails
        mydict[key] = mydict.get(key,[])+[int(data)]
    except ValueError:
        # if fails it is string key
        key = data

print mydict

This is great!!! U have integrated both of my question threads and answered here. Very many thanks for that. It gives me more interest to learn the language!!! Thank you very much for your kindness!! :) :)

Close the threads as solved, the code though short like you requested is quite difficult to read, consider updating it with well chosen names for dictionaries, describing the meaning of data, not method of implementation.

I suggested in my original answer to this point of dictionary building that conversion to int would be better way.

You could consider using the form we used in other questions for data, (default)dictionary of sets (defaultdict has default value if the key is undefined, this case empty set):

from collections import defaultdict
x = ['abc','1','2','3','def','6','8','5','13','mcg','568','35469','6453']
key = x[0]
mydict = defaultdict(set)

for data in x:
    try:
        # prove if int fails
        mydict[key].add(int(data))
    except ValueError:
        # if fails it is string key
        key = data

print mydict
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.