Python Training Knowledge Summary Series-chapter II Python data Structure Part IV-Dictionary operations

Source: Internet
Author: User

Adding and traversing Python dictionary key-value pairs

To add a key-value pair

First define an empty dictionary

dic={}
1
Assign a value directly to a key that does not exist in the dictionary to add

dic[' name ']= ' Zhangsan '
Dic
{' name ': ' Zhangsan '}
1
2
3
If key or value are variables, you can also use this method

Key= ' age '
Value=30
Dic[key]=value
Dic
{' Age ': +, ' name ': ' Zhangsan '}
1
2
3
4
5
Here you can see that the data in the dictionary is not in chronological order, if interested, you can search the data structure--hash table

You can also use the SetDefault method of the dictionary

Dic.setdefault (' sex ', ' male ')
' Male '
key= ' ID '
Value= ' 001 '
Dic.setdefault (Key,value)
' 001 '
Dic
{' id ': ' 001 ', ' Age ': ' ' name ': ' Zhangsan ', ' sex ': ' Male '}
1
2
3
4
5
6
7
8
Traverse Dictionary

There are two ways of doing this.

Method 1: Get the key first and then get the value by Dic[key]

For key in DIC:
... print ' key is%s,value%s '% (Key,dic[key])
...
Key is Id,value is 001
Key is Age,value is 30
Key is Name,value are Zhangsan
Key is Sex,value are male
1
2
3
4
5
6
7
Method 2: Sequence unpack the list of tuples returned by the dictionary items () method

For Key,value in Dic.items ():
... print ' key is%s,value%s '% (key,value)
...
Key is Id,value is 001
Key is Age,value is 30
Key is Name,value are Zhangsan
Key is Sex,value are male
1
2
3
4
5
6
7
If you are unfamiliar with lists, tuples, and sequence unpacking, it is best to get a better understanding of them by Baidu. Can be understood in combination with arrays, list classes, and hash tables in your familiar C # or Java language

Python Training Knowledge Summary Series-chapter II Python data Structure Part IV-Dictionary operations

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.