简体   繁体   English

如何从以元组为键的字典中制作以整数为键的字典

[英]How do I make a dictionary with integers as keys out of dictionary with tuples as keys

I have a dictionary in which keys are tuples (pairs): 我有一本字典,其中的键是元组(对):

dictionary1 = {(0, 1): 0, (2, 7): 3, (4, 7): 0, (1, 3): 0} 

(value means how many times does the tuple appear) (值表示元组出现多少次)

I want to transform the dictionary so that each element in the tuple will become key to the new dictionary keeping the same value as in original dict. 我想对字典进行转换,以使元组中的每个元素都将成为新字典的key ,并保持与原始字典相同的value The structure of my new dictionary should be like: 我的新字典的结构应为:

dictionary2 = {0: 0, 1: 0, 2: 3, 3: 0, 4: 0, 7: 3} 

What is the easiest/most-efficient way to do that? 最简单/最有效的方法是什么? In case tuple value appears at more than one place, the new dict will contain the sum of the values for all the tuple where it exists. 如果元组值出现在多个位置,则新字典将包含该元组所在的所有元组的值之和。

So you're basically looking for a counter. 因此,您基本上是在寻找柜台。 Lucky you, python has one in the collections module: 幸运的是,python在collections模块中有一个:

from collections import Counter

c = Counter()
for k, v in d.items():
    for i in k:
        c[i] += v

Alternatively, with a plain dictionary: 或者,使用简单的字典:

di = {}    
for k,v in d.items():
    for i in k:
        di[i] = di.get(i, 0) + v

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM