所以我的目的是从:

fruitColourMapping = [{'apple': 'red'}, {'banana': 'yellow'}]


finalMap = {'apple': 'red', 'banana': 'yellow'}

我得到的一种方法是:
 from itertools import chain
 fruits = list(chain.from_iterable([d.keys() for d in fruitColourMapping]))
 colour = list(chain.from_iterable([d.values() for d in fruitColourMapping]))
 return dict(zip(fruits, colour))

有没有更好的pythonic方法?

最佳答案

finalMap = {}
for d in fruitColourMapping:
    finalMap.update(d)

关于python - “Flattening”词典列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15647690/

10-11 19:13