Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use dict in Python Mapping Type

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to use dict in Python mapping types. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Mapping type-dict

Dictionaries can be created in several ways:

Use curly braces to separate keys: value pairs with commas: {'jack': 4098,' sjoerd': 4127} or {4098 or, 4127: 'sjoerd'}

Use dictionary deduction: {}, {x: X * * 2 for x in range (10)}

Dict_a = {key: value for key in 'python' for value in range (2)} list_phone = [(' HUAWEI', 'Huawei'), ('MI',' Xiaomi'), ('OPPO',' OPPO'), ('VIVO',' VIVO')] dict_c = {key: value for key, value in list_phone}

Use type constructors: dict (), dict ([('foo', 100), (' bar', 200)]), dict (foo=100,bar=200)

The operations supported by the dictionary:

List (d)

Returns a list of all keys used in dictionary d

Len (d)

Returns the number of items in the dictionary d

D [key]

Returns the item in d with the key key. KeyError is thrown if key does not exist in the map.

If a subclass of the dictionary defines the method _ _ missing__ () and key does not exist, the d [key] operation calls the method with the key key as an argument. D [key] then returns or throws any object or exception returned or thrown by the _ _ missing__ (key) call. No other action or method initiates a call to _ _ missing__ (). If _ _ missing__ () is not defined, KeyError is thrown. Missing () must be a method; it cannot be an instance variable:

Class Counter (dict):... Def _ _ missing__ (self, key):... Return 0 > > c = Counter () > c ['red'] 0 > c [' red'] + = 1 > c ['red'] 1

The above example shows part of the code for the collections.Counter implementation. There is another different _ _ missing__ method that is used by collections.defaultdict.

D [key] = value

Set d [key] to value.

Del d [key]

Remove d [key] from d. KeyError is thrown if key does not exist in the map.

Key in d

Returns True if the key key exists in d, or False otherwise.

Iter (d)

Returns an iterator with the key of the dictionary as the element. This is a shortcut to iter (d.keys ()).

Clear ()

Removes all elements from the dictionary.

Copy ()

Returns a shallow copy of the original dictionary

Deep copy

If you want to make the two dict completely independent, no matter how many layers of data there are. Then you need to use a tool in the python toolkit.

Import copydata = {"name": "alex", "age": 18, "scores": {"Chinese": 130," Mathematics ": 60," English ": 98,} D2 = data.copy () D3 = copy.deepcopy (data) d3 [" scores "] [" language "] = 149print (d3) print (data) classmethod fromkeys (iterable [, value]) fromkeys ()

Function is used to create a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and value is the initial value of all the keys in the dictionary

Seq = ('Google',' Runoob', 'Taobao') thisdict = dict.fromkeys (seq) print "new dictionary is:% s"% str (dict) thisdict = dict.fromkeys (seq, 10) print "new dictionary is:% s"% str (thisdict) "" new dictionary is: {' age': None, 'name': None,' sex': None} the new dictionary is: {'age': 10,' name': 10 'sex': 10} "" get (key [, default])

Returns the value of key if key exists in the dictionary, otherwise returns default. If default is not given, it defaults to None, so this method will never raise a KeyError.

Items ()

Returns the view object as a list, which is a traverable key/value pair

Dict.keys (), dict.values (), and dict.items () all return view objects (view objects), which provide a dynamic view of dictionary entities, which means that the dictionary changes and the view changes accordingly.

Tinydict = {'Name':' Runoob', 'Age': 7} print ("Value:% s"% tinydict.items ()) # Value: dict_items ([(' Age', 7), ('Name',' Runoob')]) keys ()

Returns a new view made up of dictionary keys

Dict.keys (), dict.values (), and dict.items () all return view objects (view objects), which provide a dynamic view of dictionary entities, which means that the dictionary changes and the view changes accordingly.

A = {"a": 3, "b": 2} print (a.keys ()) # pop (key [, default])

Delete the value corresponding to the given key key of the dictionary, and the return value is the deleted value.

Site= {'name':' rookie tutorial', 'alexa': 10000,' url': 'www.runoob.com'} element = site.pop (' name') print ('deleted elements are:', element) print ('dictionary is:', site) "deleted elements are: rookie tutorial dictionary: {'alexa': 10000,' url': 'www.runoob.com'}" popitem ()

The popitem () method randomly returns and deletes the last pair of keys and values in the dictionary.

If the dictionary is already empty and this method is called, a KeyError exception is reported.

Returns a key-value pair (key,value), following the LIFO (Last In First Out last-in-first-out) order rule, that is, the last key-value pair.

Site= {'name':' Rookie tutorial', 'alexa': 10000,' url': 'www.runoob.com'} pop_obj=site.popitem () print (pop_obj) print (site) reversed (d)

Returns an iterator that gets dictionary keys in reverse order. This is a shortcut to reversed (d.keys ())

Setdefault (key [, default])

The setdefault () method is similar to the get () method in that if the key does not exist in the dictionary, the key is added and the value is set to the default value.

Tinydict = {'Name':' Runoob', 'Age': 7} print ("value of Age key is:% s"% tinydict.setdefault (' Age', None)) print ("value of Sex key is:% s"% tinydict.setdefault ('Sex', None)) print ("new dictionary is:", tinydict) update ([other])

The update () function updates the key/value (key / value) pair of the dictionary parameter dict2 to the dictionary dict.

Tinydict = {'Name':' Runoob', 'Age': 7} tinydict2 = {' Sex': 'female'} tinydict.update (tinydict2) print ("update dictionary tinydict:", tinydict) values ()

Return a view object. Dict.keys (), dict.values (), and dict.items () all return view objects (view objects), which provide a dynamic view of dictionary entities, which means that the dictionary changes and the view changes accordingly.

A = {"a": 3, "b": 2} print (a.values ()) # dict_values ([3,2]) d | other

Merge keys and values in d and other to create a new dictionary, both of which must be dictionaries. When d and other have the same key, the other value takes precedence. 3.9 is supported.

A = {apple: 3, "banana": 4} b = {"grape": 5, "banana": 8} print (a | b) d | = other

Update the dictionary d with the key and value of other. Other can be a key-value pair of mapping or iterable. When d and other have the same key, the other value takes precedence.

3.9 new features

A = {"one": 1, "two": 2, "three": 3} a | = {"three": 30, "four": 4, "five": 5} print (a) a = {"apple": 3, "banana": 4} b = {"grape": 5, "banana": 8} a | = bprint (a) "{'one': 1,' two': 2, 'three': 30,' four': 4 Five': 5} {'apple': 3,' banana': 8, 'grape': 5} "Thank you for reading! This is the end of this article on "how to use dict in Python mapping types". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report