[英]Q: How get two value in two dictionary with same keys in python
i'm trying my code.我正在尝试我的代码。 I'm confused..How to combine these 2 dictionaries so that the value of the results is like this?我很困惑..如何组合这两个字典,使结果的值是这样的?
1 A 18
5 B 14
3 C 15
7 D 20
for code对于代码
d= {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e= {'A': 18, 'B': 14, 'C': 15, 'D': 20}
for k,v in d.items():
print (v)
for i,(k, v) in enumerate(e.items()):
print(i,k, v)
i don't understand.我不明白。 Please help me.请帮我。 Thanks!谢谢!
You can do this:你可以这样做:
d = {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e = {'A': 18, 'B': 14, 'C': 15, 'D': 20}
for k in sorted(d.keys() & e.keys()):
print(d[k], k, e[k])
The &
ensures that we only use the keys present in both d
and e
. &
确保我们只使用d
和e
中存在的键。
Note that we need the sorted
call to ensure that the dict
s are indexed alphabetically in the situation where the dict
keys aren't alphabetically inserted in the first place.请注意,我们需要sorted
调用以确保在dict
键没有按字母顺序插入的情况下按字母顺序dict
。
d= {'A': 1, 'B': 5, 'C': 3, 'D': 7}
e= {'A': 18, 'B': 14, 'C': 15, 'D': 20}
for i in d.keys():
print(d[i],i,e[i])
As the key in both dictionaries are same, so if you access one key you can easily access values from both the dictionaries and can print it in any order/format.由于两个字典中的键相同,因此如果您访问一个键,您可以轻松访问两个字典中的值,并可以以任何顺序/格式打印它。
d= {'A': 1, 'B': 5, 'C': 3, 'D': 7} e= {'A': 18, 'B': 14, 'C': 15, 'D': 20} final_dictionary = {x: d.get(x, 0) + e.get(x, 0) for x in set(d).union(e)} print("final dictionary", str(final_dictionary))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.