只有定义了值,Python字典才会更新 [英] Python dictionary update only if value is defined
本文介绍了只有定义了值,Python字典才会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我运行以下代码:
import json
foo = [
{
"name": "Bob",
"occupation": "",
"standing": "good",
"locations": ["California"],
"meta": { "last_updated": "2018-01-15" }
},
{
"name": "",
"occupation": "Carpenter",
"standing": "bad",
"locations": ["Arizona"],
"meta": { "last_updated": "2018-01-15", "email": "bob@domain.com" }
},
]
output = {}
for i in foo:
output.update(i)
print json.dumps(output)
最终输出是:
{
"locations": [
"Arizona"
],
"meta": {
"email": "bob@domain.com",
"last_updated": "2018-01-15"
},
"name": "",
"occupation": "Carpenter",
"standing": "bad"
}
那很好。但是,我试图弄清楚如何将一个函数传递给update方法,该方法基本上说:只有在定义了值或不为空的情况下,才进行更新。因此,在第一次迭代中,名称为 Bob,而在第二次迭代中,名称仍为Bob,因为名称实际上是未定义的。
That's pretty good. However, I'm trying to figure out how I can pass a function to the update method that basically says, "Only update if the value is defined/not empty." Therefore, on the first iteration name is "Bob", and on the second iteration name remains Bob since name is essentially undefined.
最终输出如下所示:
{
"locations": [
"Arizona"
],
"meta": {
"email": "bob@domain.com",
"last_updated": "2018-01-15"
},
"name": "Bob",
"occupation": "Carpenter",
"standing": "bad"
}
推荐答案
您可以使用以下内容过滤正在更新的新词典:
You could filter the new dictionary you are updating on, with something like:
b = {'bla': '', 'b': 77, 'c': '9'}
new_b = { k: v for k,v in b.items() if v }
new_b
不会再有 bla
作为元素。
因此,在您的情况下:
for i in foo:
output.update({ k: v for k,v in i.items() if v })
这篇关于只有定义了值,Python字典才会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文