简体   繁体   English

Python:我可以在 map function 中使用字典更新吗?

[英]Python: can I use dict update inside the map function?

I've got the following input inp = [{1:100}, {3:200}, {8:300}] and I would like to convert it to the dictionary.我有以下输入inp = [{1:100}, {3:200}, {8:300}]我想将其转换为字典。 I can do我可以

dct = dict()  
for a in inp:  
    dct.update(a)

or I can do或者我可以

_ = [dct.update(a) for a in inp]

But I would like to do something like:但我想做类似的事情:

map(dct.update, inp)

Method map builds a iterator, so the computes are made only when need it.方法map构建了一个迭代器,因此仅在需要时进行计算。 So you need to force the computing, using a list for example所以你需要强制计算,例如使用列表

list(map(dct.update, inp))
print(dct)

But you shouldn't use either the list comprehension or the map operation that are here to produce values但是您不应该使用列表推导或map操作来生成值

You'd better keep your for-loop or a dict-comprehension你最好保留你的for-loopdict-comprehension

dct = {key:val for item in inp for key,val in item.items()}

Why use map for this task?为什么使用 map 来完成这项任务?

If you want to solve it in one line you can just do:如果你想在一行中解决它,你可以这样做:

dct={k:v for x in inp for k,v in x.items()}

With using Chain Map:使用链条 Map:

from collections import ChainMap

inp = [{1: 100}, {3: 200}, {8: 300}]
data = dict(ChainMap(*inp))

What you want is reduce , not map .你想要的是reduce ,而不是map map creates a sequence by applying a function to each element of the given sequence, whereas reduce accumulates an object over the sequence. map通过将 function 应用于给定序列的每个元素来创建序列,而reduce在序列上累积 object。

from functools import reduce
inp = [{1:100}, {3:200}, {8:300}]
dct = {}
reduce(lambda d1, d2: (d1.update(d2) or d1), inp, dct)
{1: 100, 3: 200, 8: 300}

This lambda part may look tricky.这个lambda零件可能看起来很棘手。 What this does is to create a function that updates a dict and returns the dictionary itself.这样做是创建一个 function 更新字典并返回字典本身。 This is because reduce expects the accumulating function returns the updated object while dict.update() returns None .这是因为reduce期望累积 function 返回更新后的 object 而dict.update()返回None Since None is interpreted as False, the or operator returns the second variable, which is the updated dictionary.由于None被解释为 False, or运算符返回第二个变量,即更新后的字典。

This or trick is credited to @kostya-goloveshko in this thread: Why doesn't a python dict.update() return the object?这个or技巧归功于此线程中的@kostya-goloveshko: 为什么 python dict.update() 不返回 object?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM