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 define Dictionary in Python

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to define a dictionary in Python". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to define a dictionary in Python".

Dictionaries in Python are of compound data type because they are collections of objects, similar to lists.

Definition dictionary

Dictionaries are Python implementations of data structures, often referred to as associative arrays. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.

You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). The colon (:) separates each key from its associated value.

D = {:,. . . :} # define a Team > MLB_team = {... 'Colorado': 'Rockies',... 'Boston': 'Red Sox',... 'Minnesota': 'Twins',... 'Milwaukee': 'Brewers',... 'Seattle': 'Mariners'... }

You can use the built-in dict () function to build a dictionary.

D = dict ([(,), (, > > MLB_team = dict ([... ('Colorado',' Rockies'), ('Boston',' Red Sox'), ('Minnesota',' Twins'), ('Milwaukee',' Brewers'), ('Seattle',' Mariners'). ]) # another way of definition > MLB_team = dict (... Colorado='Rockies',... Boston='Red Sox',... Minnesota='Twins',... Milwaukee='Brewers',... Seattle='Mariners'... )

The display of dictionary contents.

> type (MLB_team) > MLB_team {'Colorado':' Rockies', 'Boston':' Red Sox', 'Minnesota':' Twins','Milwaukee': 'Brewers',' Seattle': 'Mariners'}

Entries in the dictionary are displayed in the defined order, and access elements cannot be specified using the index.

> MLB_team [1] Traceback (most recent call last): File ", line 1, in MLB_team [1] KeyError: 1 Dictionary access

Retrieve the value from the dictionary by specifying the corresponding key in square brackets [].

> MLB_team ['Minnesota']' Twins' > MLB_team ['Colorado']' Rockies'

If the retrieval value is not in the dictionary, an exception is thrown.

> > MLB_team ['Toronto'] Traceback (most recent call last): File ", line 1, in MLB_team [' Toronto'] KeyError: 'Toronto'

Existing dictionaries only need to assign new keys and values to add data.

> MLB_team ['Kansas City'] =' Royals' > MLB_team {'Colorado':' Rockies', 'Boston':' Red Sox', 'Minnesota':' Twins','Milwaukee': 'Brewers',' Seattle': 'Mariners',' Kansas City': 'Royals'}

To update the data, simply assign a new value to the existing key.

> MLB_team ['Seattle'] =' Seahawks' > MLB_team {'Colorado':' Rockies', 'Boston':' Red Sox', 'Minnesota':' Twins','Milwaukee': 'Brewers',' Seattle': 'Seahawks',' Kansas City': 'Royals'}

Delete the data and use del to specify the key to delete.

> del MLB_team ['Seattle'] > > MLB_team {' Colorado': 'Rockies',' Boston': 'Red Sox',' Minnesota': 'Twins','Milwaukee':' Brewers', 'Kansas City':' Royals'} Dictionary key and list Index

Some of the wrong practices that I often encounter.

> > MLB_team ['Toronto'] Traceback (most recent call last): File ", line 1, in MLB_team [' Toronto'] KeyError: 'Toronto' > MLB_team [1] Traceback (most recent call last): File", line 1, in MLB_team [1] KeyError: numbers are used as keys > d = {0:' a, 1: 'baked, 2:' cased, 3:'d'} > > d {0:'a' 1: 'baked, 2:' cased, 3:'d'} > d [0]'a'> > d [2]'c'

You cannot think of a dictionary as a list.

> type (d) > d [- 1] Traceback (most recent call last): File ", line 1, in d [- 1] KeyError:-1 > > d [0:2] Traceback (most recent call last): File", line 1, in d [0:2] TypeError: unhashable type: 'slice' > d.append (' e') Traceback (most recent call last): File ", line 1 In d.append ('e') AttributeError: 'dict' object has no attribute' append' incremental build dictionary

Create a new empty dictionary and build it by adding new keys and values one at a time.

> > person = {} > type (person) > person ['fname'] =' Joe' > person ['lname'] =' Fonebone' > person ['age'] = 51 > person [' spouse'] = 'Edna' > person [' children'] = ['Ralph',' Betty', 'Joey'] > person [' pets'] = {'dog':' Fido', 'cat':' Sox'} # create and access dictionary > > person {'fname':' Joe' 'lname':' Fonebone', 'age': 51,' spouse': 'Edna','children': [' Ralph', 'Betty',' Joey'], 'pets': {' dog': 'Fido',' cat': 'Sox'}} > person [' fname'] 'Joe' > > person [' age'] 51 > > person ['children'] [' Ralph', 'Betty'] 'Joey'] # retrieve dictionary data > > person [' children'] [- 1] 'Joey' > person [' pets'] ['cat']' Sox'

There are no clear restrictions on the data types in the built dictionary.

> foo = {42: 'aaa', 2.78:' bbb', True: 'ccc'} > foo {42:' aaa', 2.78: 'bbb', True:' ccc'} > foo [42] 'aaa' > foo [2.78]' bbb' > restrictions on ccc' dictionary keys

Almost any type of value can be used as a dictionary key in Python.

> > foo = {42: 'aaa', 2.78:' bbb', True: 'ccc'} > foo {42:' aaa', 2.78: 'bbb', True:' ccc'} # can use built-in objects such as types and functions > d = {int: 1, float: 2, bool: 3} > > d {: 1,: 2,: 3} > > d [float] 2 > > d = {bin: 1, hex: 2, oct: 3} > > d [oct] 3

Duplicate keys in the same dictionary cannot be added, and if added, the value of the original key will be replaced.

> > MLB_team = {... 'Colorado': 'Rockies',... 'Boston': 'Red Sox',... 'Minnesota': 'Twins',... 'Milwaukee': 'Brewers',... 'Seattle': 'Mariners'... } > MLB_team ['Minnesota'] =' Timberwolves' > MLB_team {'Colorado':' Rockies', 'Boston':' Red Sox', 'Minnesota':' Timberwolves','Milwaukee': 'Brewers',' Seattle': 'Mariners'}

Tuples can also be dictionary keys because tuples are immutable.

> d = {(1recover1):'a dictionary, (1, 2): 'baked, (2) 2):' d'} > d [(1))]'a' > > d [(2)]'c' dictionary value restriction

There is no limit to the value in the dictionary.

> d = {0:'a', 1:'a', 2:'a', 3:'a'} > d {0:'a', 1:'a, 2:'a, 3:'a'} > d [0] = = d [1] = = d [2] True operator and built-in function

The in and not in operator returns True or False.

> > MLB_team = {... 'Colorado': 'Rockies',... 'Boston': 'Red Sox',... 'Minnesota': 'Twins',... 'Milwaukee': 'Brewers',... 'Seattle': 'Mariners'... } > 'Milwaukee' in MLB_teamTrue >' Toronto' in MLB_teamFalse > 'Toronto' not in MLB_teamTrue

It can also be used with short circuit assessment.

> MLB_team ['Toronto'] Traceback (most recent call last): File ", line 1, in MLB_team [' Toronto'] KeyError: 'Toronto' >' Toronto' in MLB_team and MLB_team ['Toronto'] False built-in dictionary method

Like strings and lists, there are built-in methods that are called in the dictionary.

# d.clear () clear dictionary data > d = {'aquired: 10,' bounded: 20, 'clocked: 30} > > d {' aquired: 10, 'baked: 20,' clocked: 30} > d.clear () > > d {} # d.get ([,]) if there is a key in the dictionary Then return the value of the key > d = {'aqure: 10,' baked: 20, 'cased: 30} > print (d.get (' b')) 20 > print (d.get ('z')) None# is not found and an optional parameter is specified > print (d.get ('zcodes,-1))-returns the list of key-value pairs in the dictionary > d = {' aqure: 10, 'baked: 20 List (d.items ()) [('ABA, 10), (' baked, 20), ('croup, 30)] > list (d.items ()) [1] [0]' b' > list (d.items ()) [1] [1] 2percent d.keys () returns the list of keys in the dictionary > The list of values in the dictionary is returned by list (d.keys ()) ['ajar,' breadth,'c'] # d.values () returns the list of values in the dictionary > d = {'aqu: 10,' baked: 20, 'cased: 30} > d {' aquired: 10, 'baked: 20} > > d {' averse: 10, 'baked: 20} > > d List (d.values ()) [10,20,30] # d.pop ([,]) removes a key from the dictionary If it exists and returns its value > d = {'aqu: 10,' baked: 20, 'clocked: 30} > d.pop (' b') 20 > d {'aquired: 10,' cantilever: 30} # throw an exception if it doesn't exist > > d = {'aquired: 10,' baked: 20, 'cased: 30} > d.pop (' z') Traceback (most recent call last): File ", line 1 In d.pop ('z') KeyError: 'd.popitem # if the default parameter is specified, this value is returned > d = {' aqu: 10, 'baked: 20,' clocked: 30} > d.pop ('zonal,-1)-1 > > d {' aquired: 10, 'baked: 20,' cased: 30} # d.popitem () removes the key-value pair from the dictionary > > d = {'aquired: 10,' baked: 20 'd.popitem: 30} > > d.popitem () (' centering, 30) > > d {'axiu: 10,' bounded: 20} > d.popitem () ('bounded, 20) > > d {' aquired: 10} # d empty will throw an exception > > d = {} > > d.popitem () Traceback (most recent call last): File ", line 1 In d.popitem () KeyError: 'popitem (): dictionary is empty'# d.update () merges the dictionary with another dictionary or iterative key-value pair # (replaced key value). Update (substituted key value) > D1 = {' aquired: 10, 'baked: 20,' clocked: 30} > d2 = {'baked: 200,400} > d1.update (D2) > D1 {' aquired: 10, 'baked: 200 Update with tuple > D1 = {'aqqy10,' bounded: 20, 'clocked: 30} > d1.update ([(' baked, 200,400)]) > D1 {'adept: 10,' baked: 200, 'cantilevered: 30,' baked: 400} # specify keyword parameters > D1 = {'aquired: 10,' baked: 20 'Clearing: 30} > d1.update (baked 200, dumped 400) > > D1 {'axie: 10,' baked: 200, 'clocked: 30,' dumped: 400} Thank you for your reading The above is the content of "how to define a dictionary in Python". After the study of this article, I believe you have a deeper understanding of how to define a dictionary in Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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