【发布时间】:2017-08-03 21:02:32
【问题描述】:
我有两个字典,每个字典都用于计算两个列表中唯一字符串的实例数。除了有数千个条目之外,它们看起来像这样:
d1 = {'pig':10, 'cow':40, 'sheep':50}
d2 = {'pig':40, 'cow':20, 'sheep':10, 'tiger':30}
d1_total = 100 #sum of the dictionary values
d2_total = 100 #my actual dictionaries have different sums
我希望用出现在 d1 和 d2 中的键来填充新字典。我希望每个键的值是一个列表 v 具有以下内容:
v[0] = d2_value/d1_value #fold change
v[1] = d1_value/d1_total #fraction of the total count (d1)
v[2] = d2_value/d2_total #fraction of the total count (d2)
所以最终结果是:
d_new = {'pig':[4, 0.1, 0.4], 'cow':[0.5, 0.4, 0.2], 'sheep':'[0.2, 0.5, 0.1]}
我编写了以下代码,它可以运行,但是由于字典很大,执行时间太长:
def common_keys(d1, d2, d1_total, d2_total):
common = {}
for x, y in d1.iteritems():
for k, v in d2.iteritems():
d1_frac = y/d1_total
d2_frac = v/d2_total
fold_change = d2_frac/d1_frac
if x == k:
common[x] = [fold_change, d1_frac, d2_frac]
return commmon
我觉得我应该使用字典推导来提高速度,但我不知道如何从两个字典等中收集值......类似于:
common = {k:[???, (v/d1_total), (???/d2_total)] for k, v in d1.items() if k in d2.items()}
你能帮我正确地写这个吗?非常感谢您的帮助。我终于开始思考字典理解,但是当组合字典并将值修改为这样的列表时,事情变得令人困惑。
【问题讨论】:
标签: python merge dictionary-comprehension