在python中划分两个字典的值 [英] Divide the values of two dictionaries in python

查看:107
本文介绍了在python中划分两个字典的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有相同键的词典,我想对这些值进行划分,以更新或创建一个新词典,保持键不变,商为每个键的新值。

  d1 = {'a':12,'b':10,'c':2} 
d2 = {' a':0,'c':2,'b':5}
d3 = d2 / d1

d3 = {'a':0,'b' c':1}

除了重复键,值对和创建值的排序列表,然后划分,我不知道该怎么做。我希望有一个更优雅的解决方案。

解决方案

使用viewkeys(python2.7):


在d1.viewkeys()&&>中的k的

  {k:float(d2 [k])/ d1 [k] d2} 

同样在python 3(我们可以放下 float() call altogether):

  {k:d2 [k] / d1 [k] d1.keys()& d2} 

是的,我在这里使用一个关键交叉点如果您绝对确定您的密钥在两者中相同,只需使用 d2

  {k:float(d2 [k])/ d1 [k]在d2中为k} 

要完成,在Python 2.6中,您必须使用具有生成器表达式的 dict()构造函数才能实现相同的功能:

 在d2中的k的dict((k,float(d2 [k])/ d1 [k])

它生成一个键值元组序列。


I have two dictionaries with the same keys and I would like to do division on the values to update or create a new dictionary, keeping the keys intact, with the quotient as the new value for each of the keys.

d1 = { 'a':12 , 'b':10 , 'c':2 }
d2 = { 'a':0 , 'c':2 , 'b':5}
d3 = d2 / d1

d3 = { 'a':0 , 'b':0.5 , 'c':1 }

Aside from iterating through the key, value pairs and creating ordered lists of the values, then dividing, I'm not sure how to do this. I was hoping for a more elegant solution.

解决方案

Using viewkeys (python2.7):

{k: float(d2[k])/d1[k] for k in d1.viewkeys() & d2}

Same in python 3 (where we can drop the float() call altogether):

{k: d2[k]/d1[k] for k in d1.keys() & d2}

Yes, I am using a key intersection here; if you are absolutely sure your keys are the same in both, just use d2:

{k: float(d2[k])/d1[k] for k in d2}

And to be complete, In Python 2.6 and before you'll have to use a dict() constructor with a generator expression to achieve the same:

dict((k, float(d2[k])/d1[k]) for k in d2)

which generates a sequence of key-value tuples.

这篇关于在python中划分两个字典的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆