Write a python list generation

how to convert
[(a, 1), (b, 2), (a, 3)]
to
{
a: [1,3]
b: [2]
}

want to do it with a list generation. Is there any good way to do it?

Mar.20,2021

is not generated by a list:

from collections import defaultdict
s = [('a', 1), ('b', 2), ('a', 3)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)
print(d.items())

s = [('a', 1), ('b', 2), ('a', 3)]
l = {'a':[i[1] for i in s if i[0] == 'a'],
     'b':[i[1] for i in s if i[0] == 'b']
     }
Does that mean

?


this is more like the map operation of mapreduce


page 80 of "fluent Python", which is Section 3.9.3 of Chapter 3, is explicitly mentioned in "the implementation of dict and its resulting results":

  • do not iterate and modify the dictionary at the same time. Your requirements, which use dictionary generation here, will touch on here and create unexpected problems. {k: [] .append (v) for k, v in [('asides, 1), ('baked, 2), ('a', 3)]}
  • if you have to, iterate through the dictionary to get what needs to be added, put it in a new dictionary, and update the old dictionary after the iteration. It is recommended that you use the version @ vibiu @ Lin_R .

this is mainly due to the fact that the implementation of dict is determined, so it is recommended to take a look at the problem of "hash conflicts" when you have time.


personally, I think list generation is not suitable for doing these operations, and specification points will be better

from collections import defaultdict

result = defaultdict(list)
s = [('a', 1), ('b', 2), ('a', 3)]
for i in s:
    result[i[0]].append(i[1])

Thank you for your answers. I have found a better alternative

>>> from itertools import groupby
>>> from operator import itemgetter
>>> lst = [("a", 1), ("b", 2), ("a", 3)]
>>> {k: list(map(itemgetter(1), g)) for k, g in groupby(sorted(lst, key=itemgetter(0)), key=itemgetter(0))}
{'a': [1, 3], 'b': [2]}

I haven't thought of better than

According to
  @ Lotus Root Space , I don't think this is the problem with the landlord's writing. The deductive writing of the landlord is to expand the generator processed by grouby when creating the dictionary, not to modify it iteratively. 

Menu