程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[learn Python from simple to deep] dictionary

編輯:Python

The dictionary uses key value pairs (key-value) How to store , Elements can be key visit . Dictionaries are written by Curly braces { } Enclosed contains ,key : value Two parts .

One 、 Dictionary creation

# Create a dictionary 
dict1={
'name':'zhang','age':30,'city':'Beijing'}
print(dict1)

{‘name’: ‘zhang’, ‘age’: 30, ‘city’: ‘Beijing’}

Two 、 Common operations

# Get elements : adopt Key obtain value value 
dict1.get('age')

30

dict1.get('city')

‘Beijing’

Add elements

# Add elements to the dictionary 
dict1['gender']='Male'
print(dict1)

{‘name’: ‘zhang’, ‘age’: 30, ‘city’: ‘Beijing’, ‘gender’: ‘Male’}

Modifying elements

dict1['age']=35
print(dict1)

{‘name’: ‘zhang’, ‘age’: 35, ‘city’: ‘Beijing’, ‘gender’: ‘Male’}

Delete an element

# Delete an element 
del dict1['gender']
print(dict1)

{‘name’: ‘zhang’, ‘age’: 35, ‘city’: ‘Beijing’}

#items() 
dict1.items()

dict_items([(‘name’, ‘zhang’), (‘age’, 35), (‘city’, ‘Beijing’)])

# Ergodic dictionary 
for key,value in dict1.items():
print(key+":",end="")
print(value)

name:zhang
age:35
city:Beijing

dict1.keys()

dict_keys([‘name’, ‘age’, ‘city’])

for key in dict1.keys():
print(key)

name
age
city


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved