减去两个词典python的值

时间:2012-03-31 22:10:19

标签: python dictionary

这可能是一个非常天真的问题。我试图通过以下方式比较两个词典的值:

distance = dictionary1[position] - dictionary2[position]

但它不起作用,它给了我dictionary1的第一个值。

我也尝试过:

set distance = set(dictionary1[position]) - set(dictionary2[position])

但获得相同的结果。

是否可以减去如何形成两个字典的值?

字典1和2就像:

dictionary1 = {'chr1': '3434351', 'chr10': '5329532', 'chr11': '2355620',
               'chr12': '40841359', 'chr13': '101523938', 'chr14': '453255816',
               'chr17': '491453323', 'chr18': '22361089', 'chr19': '34965774',
               'chr2': '16025716', 'chr20': '295671539', 'chr21': '2067974'}

dictionary2 = {'chr1': '15845763', 'chr10': '186537818', 'chr11': '3715102',
               'chr12': '1138647613', 'chr13': '123235062', 'chr14': '68159413',
               'chr15': '51790735', 'chr16': '19324170', 'chr17': '78184979',
               'chr18': '76968073', 'chr19': '37299170', 'chr2': '18329102',
               'chr20': '31934245', 'chr22': '32679692'}

3 个答案:

答案 0 :(得分:3)

使用词典理解:

{ k:int(dic1[k]) - int(dic2[k]) for k in dic1 if k in dic2 }

或者对于Python< 2.7:

dict((k,int(dic1[k]) - int(dic2[k])) for k in dic1 if k in dic2)

答案 1 :(得分:0)

我不得不使用一种解决方法来解决两个字典中都没有的密钥问题。你应该在方便的时候照顾好这个。当密钥不存在时,我将值设置为零。

keys = dictionary1.keys()
keys.extend(dictionary2.keys())

keys = set(keys)
dic = dict()
for key in keys:
    dic[key] = int(dictionary1.get(key,0)) - int(dictionary2.get(key,0))

print dic    

的产率:

{'chr2': -2303386, 'chr1': -12411412, 'chr21': 2067974, 'chr13': -21711124, 'chr
12': -1097806254, 'chr11': -1359482, 'chr10': -181208286, 'chr17': 413268344, 'c
hr16': -19324170, 'chr15': -51790735, 'chr14': 385096403, 'chr20': 263737294, 'c
hr22': -32679692, 'chr19': -2333396, 'chr18': -54606984}

编辑正如Niklas B.在评论中指出的那样,你也可以使用dictionary comprehensions。然而,它们在蟒蛇中不可用< 2.7。

答案 2 :(得分:0)

dictionary1 = {'chr1': '3434351', 'chr10': '5329532', 'chr11': '2355620',
             'chr12': '40841359', 'chr13': '101523938', 'chr14': '453255816'}
dictionary2 = {'chr1': '15845763', 'chr10': '186537818', 'chr11': '3715102',
             'chr12': '1138647613', 'chr13': '123235062', 'chr14': '68159413'}

dictionary3 = {}

# Assuming dictionary1 and dictoinary2 are the same size and have the same key
for key in dictionary1.keys():
    if key in dictionary1:
        if key in dictionary2:
            # Calculate the new value for dictionary3, by using int()
            newValue = int(dictionary1[key]) - int(dictionary2[key])
            dictionary3[key] = newValue
        else:
            print(key, 'is not in dictionary2')
    else:
        print(key, 'is not in dictionary1')

print(dictionary3)

输出

{'chr1': -12411412, 'chr13': -21711124, 'chr12': -1097806254, 
 'chr11': -1359482, 'chr10': -181208286, 'chr14': 385096403}

我认为您可以使用int(),然后您可以将它们视为整数。我认为这是做到这一点的直接方式之一。当然,提供检查以确保存在相同的密钥(chr1x)也是一个好主意,否则它会给你错误,或者你必须找出一些东西。