在Python中的字典中,相同的键是否相互重叠? [英] Do keys that are the same override each other in a dictionary in Python?

查看:153
本文介绍了在Python中的字典中,相同的键是否相互重叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  test = { 'A1':12,'A1':13,'A1':14} 

然后测试我发现

  test ['A1'] 
14
我的问题是:将重复多次使用相同密钥的字典,在调用时选择该密钥的最后发生的实例吗? (即执行条目相互重叠)

解决方案

在Python中,字典存储非常有趣。内部字典使用哈希表实现。所以当你初始化字典时,这些是在后台执行的以下步骤:




  • 内部PyDict_New()被调用。 li>
  • 分配新对象

  • 获取可用插槽的几个步骤

  • 在添加新的键/值对时首先搜索密钥的现有哈希。如果它发现使用相同的哈希。所以如果你搜索重复的键,它会获取最后一个。



Python字典实现的好解释 http://www.laurentluce.com/posts/python-dictionary-implementation/


Keys must be unique in a dictionary, but I typed in the following assignment statement and it worked:

test = {'A1': 12, 'A1': 13, 'A1': 14}

and then testing it, I found

test['A1']
14

My question is: will dictionaries with the same key repeated multiple times choose the last occurring instance of that key when called? (i.e. Do the entries override each other)

解决方案

In Python, Dictionary storage is very interesting. Internally dictionaries are implemented using hash tables. So when you initialise a dictionary , these are the following steps that takes place in the background:

  • Internally PyDict_New() is called.
  • Allocation of new object
  • Few steps for getting available slots
  • While adding a new key/value pair it first searches for existing hash for the key. If it finds then use the same hash. So if you search for duplicate key , it fetches the lastest one.

Nice explanation for Python dictionary implementation http://www.laurentluce.com/posts/python-dictionary-implementation/

这篇关于在Python中的字典中,相同的键是否相互重叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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