未加星标

Handling missing keys in Python dictionaries

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二03 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

In python,dictionaries are containers which map one key to its value with access time complexity to be O(1) . But in many applications, the user doesn’t know all the keys present in the dictionaries. In such instances, if user tries to access a missing key, an error is popped indicating missing keys .

# Python code to demonstrate Dictionary and
# missing value error
# initializing Dictionary
d = { 'a' : 1 , 'b' : 2 }
# trying to output value of absent key
print ("The value associated with 'c' is : ")
print (d['c'])

Error :

Traceback (most recent call last):
File "46a9aac96614587f5b794e451a8f4f5f.py", line 9, in
print (d['c'])
KeyError: 'c'

In the above example, no key named ‘c’ in dictionary, popped a runtime error. To avoid such conditions, and to make aware user that a particular key is absent or to pop a default message in that place, there are several methods to handle missing keys.

Method 1 : Using get()

get(key,def_val)method is useful when we have to check for the key. If the key is present, value associated with the key is printed, else the def_value passed in arguments is returned.

Method 2 : Using setdefault()

setdefault(key, def_value)works in a similar way as get(), but the difference is that each time a key is absent, a new key is created with the def_value associated to the key passed in arguments.

For implementation of above functions, clickhere.

Method 3 : Using defaultdict

“ defaultdict ” is a container that is defined in module named “ collections “. It takes a function(default factory) as its argument . By default, default factory is set to “int” i.e 0 . If a key is not present is defaultdict, the default factory value is returned and displayed. It has advantages over get() or setdefault().

A default value is set at the declaration . There is no need to invoke the function again and again and pass similar value as arguments. Hence saving time . The implementation of defaultdict is faster than get() or setdefault(). # Python code to demonstrate defaultdict
# importing "collections" for defaultdict
import collections
# declaring defaultdict
# sets default value 'Key Not found' to absent keys
defd = collections.defaultdict(lambda : 'Key Not found')
# initializing values
defd['a'] = 1
# initializing values
defd['b'] = 2
# printing value
print ("The value associated with 'a' is : ",end="")
print (defd['a'])
# printing value associated with 'c'
print ("The value associated with 'c' is : ",end="")
print (defd['c'])

Output :

The value associated with 'a' is : 1
The value associated with 'c' is : Key Not found

This article is contributed by Manjeet Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: Python
分页:12
转载请注明
本文标题:Handling missing keys in Python dictionaries
本站链接:http://www.codesec.net/view/482049.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(27)