Adding and traversing methods for key-value pairs in Python dictionaries _python

Source: Internet
Author: User
Tags hash in python

Add a key value pair

Define an empty dictionary first

>>> dic={}

To add a key that does not exist in the dictionary directly.

>>> dic[' name ']= ' Zhangsan '
>>> dic

{' name ': ' Zhangsan '}

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

>>> key= ' age '
>>> value=30
>>> dic[key]=value
>>> dic

{' Age ': ' Name ': ' Zhangsan '}

Here you can see the data in the dictionary is not in order, if interested, you can search the data structure of--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 '}

Traverse Dictionary

There are two ways of doing this.

Method 1: get the key first, then get value via Dic[key]

>>> for key in dic:
...   print ' key is%s,value '%s '% (Key,dic[key])
...
The key is Id,value is 001 The key is Age,value is-is-
Name,value is Zhangsan The key 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) ...
The key is Id,value is 001 The key is Age,value is-is-
Name,value is Zhangsan The key is Sex,value is
male

If you are unfamiliar with lists, tuples, and sequences, it is best to have a look at Baidu and understand them in depth. Can be understood in conjunction with arrays, list classes, and hash tables in your familiar C # or Java language

The above Python dictionary key value pairs of add and traverse method is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.

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.