Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字典对应键的操作_Python_Dictionary - Fatal编程技术网

Python 字典对应键的操作

Python 字典对应键的操作,python,dictionary,Python,Dictionary,我有一些大型python字典,看起来可能是: dict1 = {2015: 5, 2017: 10, 2018; 20} dict2 = {2015: 35, 2017: 80, 2018; 40} 这两本字典都有相同的键 我想生成以下内容: dict3 = {2015: 7, 2017: 8, 2018: 2} #dict2 divided by dict1 for corresponding keys 有没有一种方法可以在不使用循环键的情况下实现上述功能?您可以编写一个简单的dict理解

我有一些大型python字典,看起来可能是:

dict1 = {2015: 5, 2017: 10, 2018; 20}
dict2 = {2015: 35, 2017: 80, 2018; 40}
这两本字典都有相同的键

我想生成以下内容:

dict3 = {2015: 7, 2017: 8, 2018: 2} #dict2 divided by dict1 for corresponding keys
有没有一种方法可以在不使用循环键的情况下实现上述功能?

您可以编写一个简单的dict理解表达式,并在任何dict的键上进行迭代,如下所示:

你可以用听写理解表达来实现它

在Python 3中,预测两个int返回float为:

为了获得int,必须显式地键入cast,如下所示:

>>> {k:int(dict2[k]/dict1[k]) for k in dict2}
{2017: 8, 2018: 2, 2015: 7}
在Python 2中,情况并非如此。您只需执行以下操作:

>>> {k:dict2[k]/dict1[k] for k in dict2}
{2017: 8, 2018: 2, 2015: 7}

为什么没有for循环?你的意思是一般不使用循环,还是只是想暂时使用类似的替代方法?我希望避免任何循环,因为字典很大,所以遍历每个键可能会很昂贵。由于需要对两个字典中的每个值执行除法,那么你可能必须使用某种类型的循环。即使你以某种方式避免了一个循环,你仍然需要看看线性时间上给出的所有值,与循环相同。这个线性时间是我希望避免的。唯一的其他方法可能是使用多处理。
>>> {k:int(dict2[k]/dict1[k]) for k in dict2}
{2017: 8, 2018: 2, 2015: 7}
>>> {k:dict2[k]/dict1[k] for k in dict2}
{2017: 8, 2018: 2, 2015: 7}