0

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?

2
Contributors
13
Replies
14
Views
7 Years
Discussion Span
Last Post by pyTony
Featured Replies
  • 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: [CODE]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 … Read More

  • 1

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

  • 1

    Maybe something like this is efficient enough, I change numbers to real numbers and data structure to set (to avoid doubles) [CODE]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] … Read More

  • 1

    [QUOTE=tonyjv;1380967]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: [/QUOTE] Neater way if you like numbers to be really numbers: [CODE]x = ['abc','1','2','3','def','6','8','5','13','mcg','568','35469','6453'] key = x[0] mydict = dict() for … Read More

  • 1

    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 … Read More

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:

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

Edited by pyTony: n/a

0

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.

1

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

0

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

0

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']}

Edited by knan: n/a

0

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.

0

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???

Edited by knan: n/a

0

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.

Edited by pyTony: n/a

0

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?

Edited by knan: n/a

1

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

Edited by pyTony: n/a

Votes + Comments
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

Edited by pyTony: n/a

0

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!! :) :)

Edited by knan: n/a

1

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

Edited by pyTony: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.