python 字典数据结构_Python字典数据结构介绍

python 字典数据结构

Dictionary is one of the most used data structures in Python. A dictionary is an unordered collection of items and we usually have keys and values stored in a dictionary. Let us look at a few examples for how the dictionary is usually used.

字典是Python中最常用的数据结构之一。 字典是项目的无序集合,我们通常将键和值存储在字典中。 让我们看一些通常如何使用字典的示例。

# dictionary declaration 1
dict1 = dict()

# dictionary declaration 2
dict2 = {}

# Add items to the dictionary
# The syntax to add and retrieve items is same for either of the two objects we defined above. 
key = "X"
value = "Y"
dict1[key] = value

# The dictionary doesn't have any specific data-type. 
# So, the values can be pretty diverse. 
dict1[key] = dict2

Let’s now look at some retrieval ways.

现在让我们看一下一些检索方式。

# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]

# This key doesn't exist in the dictionary. 
# So, we will get a `KeyError`
value = dict1["random"]

避免KeyError:使用.get函数 (Avoiding KeyError: Use .get function)

In case the given key does not exist in the dictionary, Python will throw a KeyError. There is a simple workaround for this. Let’s look at how we can avoid KeyError using the in-built .get function for dictionaries.

如果给定的键在字典中不存在,Python将抛出KeyError 。 有一个简单的解决方法。 让我们看看我们如何能够避免KeyError使用内置.get功能的词典。

dict_ = {}

# Some random key
random_key = "random"

# The most basic way of doing this is to check if the key 
# exists in the dictionary or not and only retrieve if the 
# key exists. Otherwise not. 
if random_key in dict_:
  print(dict_[random_key])
else:
  print("Key = {} doesn't exist in the dictionary".format(dict_))

A lot of times we are ok getting a default value when the key doesn’t exist. For e.g. when building a counter. There is a better way to get default values from the dictionary in case of missing keys rather than relying on standard if-else.

很多时候,当键不存在时,我们可以获取默认值。 例如在建立柜台时。 在缺少键的情况下,有一种更好的方法从字典中获取默认值,而不是依赖于标准的if-else

# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]

freq = {}

for item in arr:
  # Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
  freq[item] = freq.get(item, 0) + 1

So, the get(<key>, <defaultval>) is a handy operation for retrieving the default value for any given key from the dictionary. The problem with this method comes when we want to deal with mutable data structures as values e.g. list or set.

因此, get(<key>, <defaultval>)是一个方便的操作,用于从字典中检索任何给定键的默认值。 当我们想将可变数据结构作为值(例如listset处理时,这种方法就会出现问题。

dict_ = {}

# Some random key
random_key = "random"

dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}

dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}

Did you see the problem?

你看到问题了吗?

The new set or the list doesn’t get assigned to the dictionary’s key. We should assign a new list or a set to the key in case of missing value and then append or add respectively. Ley’s look at an example for this.

setlist未分配给词典的键。 如果缺少值,我们应该为键分配一个新list或一个set ,然后分别appendadd 。 Ley为此举了一个例子。

dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!

避免KeyError:使用defaultdict (Avoiding KeyError: Use defaultdict)

This works most of the times. However, there is a better way to do this. A more pythonic way. The defaultdict is a subclass of the built-in dict class. The defaultdict simply assigns the default value that we specify in case of a missing key. So, the two steps:

这在大多数情况下都有效。 但是,有一种更好的方法可以做到这一点。 一种更pythonic方式。 defaultdict是内置dict类的子类。 defaultdict只是分配我们在缺少键时指定的默认值。 因此,分两个步骤:

dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")

can now be combined into one single step. For e.g.

现在可以合并为一个步骤。 例如

from collections import defaultdict

# Yet another random key
random_key = "random_key"

# list defaultdict
list_dict_ = defaultdict(list)

# set defaultdict
set_dict_ = defaultdict(set)

# integer defaultdict
int_dict_ = defaultdict(int)

list_dict_[random_key].append("Hello World!")
set_dict_[random_key].add("Hello World!")
int_dict_[random_key] += 1

"""
  defaultdict(<class 'list'>, {'random_key': ['Hello World!']}) 
  defaultdict(<class 'set'>, {'random_key': {'Hello World!'}}) 
  defaultdict(<class 'int'>, {'random_key': 1})
"""
print(list_dict_, set_dict_, int_dict_)

Official Docs

官方文件

翻译自: https://www.freecodecamp.org/news/python-dictionary-data-structure-explained/

python 字典数据结构

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值