Do not get the value in square brackets dictionary in Python, try this method


The full text 2254 words, when learning is expected to grow 7 Fenzhong

Source: Pexels

The dictionary is elementary education period, we can not get a good helper

Unordered dictionary is a collection of terms and definitions, this means:

 

· Each data point has an identifier (i.e., terms), and the value (i.e. defined).

· The terms in the dictionary must be unique, can not be repeated.

· The list is different, these terms are not explicitly order.

 

Braces dictionary definitions, definitions of terms or separated by commas.

 

author = {   "first_name":"Jonathan",   "last_name":"Hsu",   "username":"jhsu98"}

Access dictionary value of the old (bad) method

 

In the conventional method dictionary values accessed using square bracket notation. Such nested syntax names of the terms in square brackets, as shown below.

 

author = {   "first_name":"Jonathan",   "last_name":"Hsu",   "username":"jhsu98"}print(author['username']) # jhsu98print(author['middle_initial']) # KeyError: 'middle_initial'

Tries to reference the term does not exist will cause KeyError. This could cause serious problems, especially when dealing with unpredictable business data.

 

Although we can package our statement in the try / except or if statement, but more suitable for stacking dictionary terms.

 

author = {}try:   print(author['username'])except KeyError as e:   print(e) # 'username'ifauthor['username']:   print(author['username'])

If you have JavaScript background, reference value with a point symbol dictionary may very attractive. This does not work in Python.

 

author = {   "first_name":"Jonathan",   "last_name":"Hsu",   "username":"jhsu98"}print(author.username)# AttributeError: 'dict' object has no attribute 'username'

 

Use .get () method

 

Source: Pexels

When you want to access the value of the dictionary, the safest method is to use the .get () method. This function takes two parameters:

 

• First (required): name search term needs. Or it can be a string variable, allowing dynamic search terms.

· A second (optional): If the term is not present, the default value is used.

 

author = {   "first_name":"Jonathan",   "last_name":"Hsu",   "username":"jhsu98"}print(author.get('username')) # jhsu98print(author.get('middle_initial', None)) # None

If the term has been previously announced, the .get () works with the traditional square brackets cited no different. If the term is not defined, a default value is returned, eliminating the need to handle the exception.

 

这个默认值可以是任何值,但请记住它是可选的。如果没有包含默认值,则使用Python里空值的等效值None。

 

使用.setdefault()方法

 

有时候,不仅希望避免在字典中出现未定义的术语,还希望代码能够自动纠正其数据结构。.setdefault()的结构与.get()相同。但是,当术语未定义时,除了返回默认值之外,字典的术语也将设置为该值。

 

author = {   "first_name":"Jonathan",   "last_name":"Hsu",   "username":"jhsu98"}print(author.setdefault('username')) # jhsu98print(author.setdefault('middle_initial', None)) # None

上述例子可见,在术语存在时,.setdefault()与方括号表示法或.get()相同。不仅如此,当术语不存在时,它与.get()一样返回传递的默认值。

 

它与.get()不同在于,它的术语和定义现在是字典的一部分,如下所示。

 

author = {   "first_name":"Jonathan",   "last_name":"Hsu",   "username":"jhsu98"}print(author.setdefault('middle_initial',None)) # Noneprint(author)"""{  'first_name': 'Jonathan',  'last_name': 'Hsu',  'username': 'jhsu98',  'middle_initial': None}""

.get()和.setdefault() 都是引用字典值时的优秀技术......只是需要一些时间打破旧习惯,采用这种做法。

 

来源:Pexels

如果不想修改原始数据时,.get()就是你的不二选择。

 

如果要更改原始数据,使用.setdefault(),然后大功告成。


推荐阅读专题

留言点赞发个朋友圈

我们一起分享AI学习与发展的干货

编译组:王品一、刘鉴楠

相关链接:

https://medium.com/better-programming/stop-using-square-bracket-notation-to-get-a-dictionarys-value-in-python-c617f6ea15a3

如转载,请后台留言,遵守转载规范

推荐文章阅读

ACL2018论文集50篇解读

EMNLP2017论文集28篇论文解读

2018年AI三大顶会中国学术成果全链接

ACL2017论文集:34篇解读干货全在这里

10篇AAAI2017经典论文回顾

长按识别二维码可添加关注

读芯君爱你

发布了768 篇原创文章 · 获赞 2447 · 访问量 38万+

Guess you like

Origin blog.csdn.net/duxinshuxiaobian/article/details/104191211