Python Learning Notes (dictionary)

Source: Internet
Author: User

1. The dictionary provides a mapping between Key-value and supports the following basic operations:

x = d[k] Indexed by key

D[K] = x is assigned by key

Del D[k] Deletes an item by key

K in D checks if a key exists

Len (d) Number of items in the dictionary

2. How to create an empty dictionary

D = {}

D = dict ()

3. Efficient Use of dictionary lists

[1] using in to check if key exists , avoid using the Has_key () method, Has_key () method has been removed in Python3

[2] using the Get (Key,default) method to obtain value, when key does not exist, D[k] way to access value, will throw a Keyerror exception, in order to avoid or handle the exception, need to add additional code, and use Get (key, Default) method, the code is more concise and beautiful

## # bad # #D = {'name':'python'}defFoo (key,default='default'):    ifKeyinchD:returnD[key]Else:        returndefaultPrint(Foo ('name'))#>>>pythonPrint(Foo ('Wrongname'))#>>>defaultdefFoo (key,default='default'):    Try:        returnD[key]exceptKeyerror as E:returndefaultPrint(Foo ('name'))#>>>pythonPrint(Foo ('Wrongname'))#>>>default
Bad Code
## # good # #D = {'name':'python'}Print(D.get ('name','default'))#>>>pythonPrint(D.get ('Wrongname','default'))#>>>default
Good Code

[3] using the SetDefault (Key,default) method to set the default value for a nonexistent key, when key exists, return key corresponding value, equivalent to D[k] or d.get (k), when key does not exist, equivalent to D[k]=default, and returns the default

When doing categorical statistics, you want to classify the same type of data into some type of dictionary, and then reassemble the same type of thing in a list, and get a new dictionary

data = [
("Animal", "Bear"),
("Animal", "duck"),
("Plant", "Cactus"),
("Vehicle", "Speed Boat"),
("Vehicle", "school Bus")
]

Converted Into

data = {
' Plant ': [' Cactus '],
' Animal ': [' bear ', ' duck '],
' Vehicle ': [' Speed boat ', ' school bus ']
}
data = [    ("Animal"," Bear"),    ("Animal","Duck"),    ("Plant","Cactus"),    ("Vehicle","Speed Boat"),    ("Vehicle","School Bus")]group= {} for(Key, value)inchdata:a=[] Group.get (Key, a). Append (value)ifKey not inchGroup:group[key]=aPrint(group)#>>>{' animal ': [' bear ', ' duck '], ' plant ': [' cactus '], ' vehicle ': [' Speed boat ', ' school Bus ']}Group= {} for(Key, value)inchData:ifKey not inchGroup:group[key]=[value]Else: Group[key].append (value)Print(group)#>>>{' animal ': [' bear ', ' duck '], ' plant ': [' cactus '], ' vehicle ': [' Speed boat ', ' school Bus ']}
Bad Code
data = [    ("Animal"," Bear"),    ("Animal","Duck"),    ("Plant","Cactus"),    ("Vehicle","Speed Boat"),    ("Vehicle","School Bus")]group= {} for(Key, value)inchData:group.setdefault (key, []). Append (value)Print(group)#>>>{' animal ': [' bear ', ' duck '], ' plant ': [' cactus '], ' vehicle ': [' Speed boat ', ' school Bus ']}
Good Code

Reference Documentation:

Official Guidance Https://docs.python.org/3/library/stdtypes.html#mapping-types-dict

Checklist for efficient use of Python dictionaries https://foofish.net/how-to-python-dict.html

Python reference manual

Python Learning Notes (dictionary)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.