从2个列表创建字典
我想根据我拥有的三个列表创建一个字典:
Hier = ['A', 'C']
values = [10, 20]
All = ['A', 'B', 'C', 'D']
结果应如下所示:
{"A", 10, "B": "", "C": 20, "D":""}
回答
尝试:
Hier = ["A", "C"]
values = [10, 20]
All = ["A", "B", "C", "D"]
d = dict.fromkeys(All, "")
d.update(zip(Hier, values))
print(d)
印刷:
{'A': 10, 'B': '', 'C': 20, 'D': ''}
编辑:dict()从.update
- Minor improvement: Drop the temporary `dict` for the `update` call; `update` accepts an iterable of key/value pairs, so it could read from the `zip` iterator directly: `d.update(zip(Hier, values))`