python dict理解是否总是“最后获胜"?如果有重复的密钥 [英] Is a python dict comprehension always "last wins" if there are duplicate keys

查看:85
本文介绍了python dict理解是否总是“最后获胜"?如果有重复的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我用dict理解创建了一个python字典,但是有重复的键,我是否保证最后一项将最终出现在最终字典中?从 https://www.python.org/dev/peps/pep-0274/?

If I create a python dictionary with a dict comprehension, but there are duplicate keys, am I guaranteed that the last item will the the one that ends up in the final dictionary? It's not clear to me from looking at https://www.python.org/dev/peps/pep-0274/?

new_dict = {k:v for k,v in [(1,100),(2,200),(3,300),(1,111)]}
new_dict[1] #is this guaranteed to be 111, rather than 100?

推荐答案

密钥的最后一个值获胜.我可以在 Python 3语言参考中找到最好的文档,第6.2.7节:

The last value for a key wins. The best documentation I can find for this is in the Python 3 language reference, section 6.2.7:

与列表和集合理解相反,字典理解需要两个表达式之间用冒号分隔,后跟通常的"for"和"if"子句.运行理解时,将生成的键和值元素按其生成的顺序插入到新字典中.

该文档还明确指出,对于逗号分隔的键/值对({1: 1, 1: 2})和字典解压缩({**{1: 1}, **{1: 2}}),最后一项将获胜:

That documentation also explicitly states that the last item wins for comma-separated key-value pairs ({1: 1, 1: 2}) and for dictionary unpacking ({**{1: 1}, **{1: 2}}):

如果给出了一个逗号分隔的键/基准对序列,则...您可以在键/基准列表中多次指定相同的键,并且该键的最终字典值将是最后一个给出的键.

If a comma-separated sequence of key/datum pairs is given, ... you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given.

双星号**表示字典解包.它的操作数必须是一个映射.每个映射项都添加到新词典中.较新的值将替换较早的键/基准对和较早的字典解包已设置的值.

A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.

请注意,正如wim所指出的,如果有相同但截然不同的钥匙,则第一个版本的钥匙将获胜:

Note that as wim points out, the first version of a key wins if there are equal but distinct keys:

>>> {k: v for k, v in [(1, 1), (1.0, 2.0)]}
{1: 2.0}

在这里,最终的字典具有来自(1, 1)的键,但是具有来自(1.0, 2.0)的值.

Here, the final dict has the key from (1, 1), but the value from (1.0, 2.0).

这篇关于python dict理解是否总是“最后获胜"?如果有重复的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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