(Feb-26-2019, 04:45 PM)ichabod801 Wrote: [ -> ]One thing you can do is just delete line 11. Leave what is now line 12 indented and it will still work.
Another solution is collections.defaultdict:
import collections
l = [[233,'a'],[321,'a'],[445,'b'],[322,'c'],[123,'c'],[12312,'c'],[456,'d'],[334,'e']]
ND = collections.defaultdict(list)
for x in l:
ND[x[1]].append(x[0])
Thank you for the solution. But I'm using IronPython, trying to import as less as I can.
D = ['a', 'b', 'c', 'd', 'e']
l = [[233, 'a'], [321, 'a'], [445, 'b'], [322, 'c'], [123, 'c'], [12312, 'c'], [456, 'd'], [334, 'e']]
ND = dict.fromkeys(D,[])
print (ND)
for x in l:
ND[x[1]].append(x[0])
print(ND)
I tried using dict.fromkeys, but it give me a different result. It will put all x[0] under each key of the dictionary. Comparing with the script below, their first "print" give same kind of dictionary. Their second steps are the same. Could anyone tell me why the results are different?
D = ['a', 'b', 'c', 'd', 'e']
l = [[233, 'a'], [321, 'a'], [445, 'b'], [322, 'c'], [123, 'c'], [12312, 'c'], [456, 'd'], [334, 'e']]
ND = {}
for x in l:
if x[1] in D:
ND[x[1]] = []
print (ND)
for x in l:
ND[x[1]].append(x[0])
print(ND)