Python Basics-Dictionary (dictionary)

Source: Internet
Author: User

1. Dictionary definition, key unique, value arbitrary

dic={key0:value0,key1:value1}

2. Output

print(dic[key0])>>:value0

3. Traversing a dictionary
3.1keys () traverse the key in the dictionary

dic={‘name‘:‘zhangsan‘,‘age‘:20}for k in dic.keys():    print(k)>>:nameage             

3.2values () traverse the value in the dictionary

dic={‘name‘:‘zhangsan‘,‘age‘:20}for v in dic.values():    print(v)>>:zhangsan20

3.3items () traversing the key,value in the dictionary

dic={‘name‘:‘zhangsan‘,‘age‘:20}for k,v in dic.items():    print(k+‘:‘+str(v))>>:name:zhangsanage:20      

4. Dictionary Insert Element

dic={‘name‘:‘zhangsan‘,‘age‘:20}dic[‘job‘]=‘python‘print(dic)>>:{‘name‘: ‘zhangsan‘, ‘age‘: 20, ‘job‘: ‘python‘}

5. Modify values by key

dic={‘name‘:‘zhangsan‘,‘age‘:20}dic[‘name‘]=‘lisi‘print(dic)>>:{‘name‘: ‘lisi‘, ‘age‘: 20}

6.pop () Remove elements from the dictionary

dic={‘name‘:‘zhangsan‘,‘age‘:20}dic.pop(‘name‘)print(dic)>>:{‘age‘: 20}

7. Interpret whether the element is in the dictionary:

dic={‘name‘:‘zhangsan‘,‘age‘:20}tmp=‘name‘if tmp in dic:#和 if  tmp in dic.keys()相同:    print("%s in dic" %tmp)#判断元组是否在值中if tmp in dic.values():    print("%s in dic" %tmp)

Python Basics-Dictionary (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.