In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how python access the Dict dictionary, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
Access Dict Dictionary
You will also often write key,value (key, value) to dicts.
If you try to access a key that does not exist in dict, you may be inclined to do this to avoid KeyError errors:
Countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: if i in countr: countr [I] + = 1 else: countr [I] = 1for i in range (10): if i in countr: print ("Count of {}: {}" .format (I, format [I)) else: print ("Count of {}: {}" .format (I, 0))
However, using get () is a better approach.
Countr = {} bag = [2,3,1,2,5,6,7,9,2,7] for i in bag: countr [I] = countr.get (I, 0) + 1for i in range (10): print ("Count of {}: {}" .format (I, countr.get (I, 0)
Of course, you can use setdefault instead.
This is also done in a simpler but more expensive way:
Bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] # {2: 3, 3: 1, 1: 1, 5: 1, 6: 1, 7: 2, 9: 1} countr = dict ([(num, bag.count (num) for num in bag]) for i in range (10): print ("Count of {}: {}" .format (I, countr.get (0)
You can also use dict deduction.
Countr = {num: bag.count (num) for num in bag}
These two methods are expensive because they traverse the list each time count is called.
The above is all the contents of the article "how to access the Dict Dictionary by python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.