gpt4 book ai didi

仅当定义了值时才更新 Python 字典

转载 作者:行者123 更新时间:2023-12-05 09:17:20 29 4
gpt4 key购买 nike

如果我运行以下代码:

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"
}

这还不错。但是,我试图弄清楚如何将一个函数传递给更新方法,该方法基本上表示“仅在值已定义/不为空时更新”。因此,在第一次迭代中名称为“Bob”,而在第二次迭代中名称仍为 Bob,因为名称本质上是未定义的。

最终输出如下所示:

{
"locations": [
"Arizona"
],
"meta": {
"email": "bob@domain.com",
"last_updated": "2018-01-15"
},
"name": "Bob",
"occupation": "Carpenter",
"standing": "bad"
}

最佳答案

你可以过滤你正在更新的新词典,像这样:

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 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48391502/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com