How to add and Traverse Python dictionary key-value pairs

Source: Internet
Author: User
to add a key-value pair

First define an empty dictionary

>>> dic={}

Assign a value directly to a key that does not exist in the dictionary to add

>>> dic[' name ']= ' Zhangsan ' >>> dic{' name ': ' Zhangsan '}

If key or value are variables, you can also use this method

>>> key= ' age ' >>> value=30>>> dic[key]=value>>> dic{' age ': ' Name ': ' Zhangsan '}

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 ': ' The ' name ': ' Zhangsan ', ' sex ': ' Male '}

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 are 001key is Age,value are 30key is Name,value Y is Sex,value is male

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 are 001key is Age,value are 30key is name,value it zhangsankey I S Sex,value is male

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

Above this Python dictionary key value pair's addition and the traversal method is the small part to share to everybody's whole content, hoped can give everybody a reference, also hoped that everybody many support topic.alibabacloud.com.

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.