【发布时间】:2021-06-26 14:54:08
【问题描述】:
我需要找到一种方法从一个字典获取值到另一个字典,基于键名匹配而不使用两个循环 \if 语句。
主要目标是让它更高效地运行,因为它是更大代码的一部分并在多个线程上运行。
如果你能保持字典结构会有所帮助
第二个字典在高级中用值 0 初始化
dict_1 = {
"school": {
"main": ["first_key"]
},
"specific": {
"students": [
{
"name": "sam",
"age": 13
},
{
"name": "dan",
"age": 9
},
{
"name": "david",
"age": 20
},
{
"name": "mike",
"age": 5
}
],
"total_students": 4
}
}
dict_2 = {'sam': 0, 'mike': 0, 'david': 0, 'dan': 0, 'total_students': 0}
for i in dict_1["specific"]['students']:
for x in dict_2:
if x == i["name"]:
dict_2[x] = i["age"]
dict_2["total_students"] = dict_1["specific"]["total_students"]
print(dict_2)
还有更优雅的方法吗?
谢谢!!
【问题讨论】:
标签: python loops dictionary if-statement