python基礎:字典操作


在Python中,字典是一系列鍵—值對 。每個鍵都與一個值相關聯,可以使用鍵來訪問與之相關聯的值。與鍵相關聯的值可以是數字、字符串、列表乃至字典。事實上,可將任何Python對象用作字典中的值。字典用放在花括號 { } 中的一系列鍵—值對錶示

創建並訪問字典

people = {'姓名':'王小二','年齡':18}
print(people['姓名'])
print(people['年齡'])
print(people['姓名'] + '是' + str(people['年齡']) + '歲!')
'''
王小二
18
王小二是18歲!
'''

添加鍵—值對

字典是一種動態結構,可隨時在其中添加鍵—值對。要添加鍵—值對,可依次指定字典名、用方括號括起的鍵和相關聯的值。

people = {'姓名':'王小二','年齡':18}
print(people)

people['國家'] = '中國'
people['省份'] = '山東'
print(people)

'''
{'姓名': '王小二', '年齡': 18}
{'姓名': '王小二', '年齡': 18, '國家': '中國', '省份': '山東'}
'''

或者先創建一個空字典,然後在添加內容:出現了問題

people = {}
#print(peolpe)
people['name'] = 'wang'
people['age'] = 18
print(peolpe)

'''
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-48ebe2c92dee> in <module>()
      3 people['name'] = 'wang'
      4 people['age'] = 18
----> 5 print(peolpe)

NameError: name 'peolpe' is not defined

'''

修改字典中的值

要修改字典中的值,可依次指定字典名、用方括號括起的鍵以及與該鍵相關聯的新值。

people = {'姓名':'王小二','年齡':18}
print(people)
people['年齡'] = 19
print(people)
'''
{'姓名': '王小二', '年齡': 18}
{'姓名': '王小二', '年齡': 19}
'''

刪除鍵—值對

使用del 語句將相應的鍵—值對徹底刪除。使用del 語句時,必須指定字典名和要刪除的鍵。刪除的鍵—值對永遠消失了

people = {'姓名':'王小二','年齡':18}
print(people)
del people['姓名']
print(people)
'''
{'姓名': '王小二', '年齡': 18}
{'年齡': 18}
'''

由類似對象組成的字典

favorite_languages={
    'simth':['python','c'],
    'bob':'c',
    'bill':['matlab','java'],
    'marry':['r','java','c++']
    }
print(favorite_languages)
print('\n')
print( favorite_languages['simth'])

'''
{'simth': ['python', 'c'], 'bob': 'c', 'bill': ['matlab', 'java'], 'marry': ['r', 'java', 'c++']}

['python', 'c']
'''

遍歷字典

可遍歷字典的所有鍵—值對、鍵或值。

遍歷所有的鍵—值對 : dictionary.items()

字典名和方法items() 返回一個鍵—值對列表。注意,即便遍歷字典時,—值對的返回順序也與存儲順序不同

people = {'姓名': '王小二', '年齡': 18, '國家': '中國', '省份': '山東'}
for key,value in people.items():
    print("\nKey:" + key)
    print("Value:" + str(value))
    
'''
注意,即便遍歷字典時,—值對的返回順序也與存儲順序不同
Key:姓名
Value:王小二

Key:年齡
Value:18

Key:國家
Value:中國

Key:省份
Value:山東
'''

遍歷字典中的所有鍵:dictionary.keys()

遍歷字典時,會默認遍歷所有的鍵,因此,如果將上述代碼中的for name infavorite_languages.keys(): 替換爲for name in favorite_languages: ,輸出將不變。如果顯式地使用方法keys() 可讓代碼更容易理解.

favorite_languages={
    'simth':['python','c'],
    'bob':'c',
    'bill':['matlab','java'],
    'marry':['r','java','c++']
    }

for name in favorite_languages.keys():
    print(name.title())
    
'''
Simth
Bob
Bill
Marry
'''    

按順序遍歷字典中的所有鍵:sorted()

favorite_languages={
    'simth':['python','c'],
    'bob':'c',
    'bill':['matlab','java'],
    'marry':['r','java','c++']
    }

for name in sorted(favorite_languages.keys()):
    print(name.title())
    
'''
Bill
Bob
Marry
Simth
'''

遍歷字典中的所有值:dictionary.values()

方法values() ,它返回一個值列表,而不包含任何鍵。

favorite_languages={
    'simth':'python',
    'bob':'c',
    'bill':'matlab',
    'marry':'python',
    }
print("The following languages have been mentioned:\n")
for language in favorite_languages.values():
    print(language.title())
    
'''
The following languages have been mentioned:

Python
C
Matlab
Python
'''

上述做法提取字典中所有的值,而沒有考慮是否重複。涉及的值很少時,這也許不是問題,但如果被調查者很多,最終的列表可能包含大量的重複項。爲剔除重複項,可使用集合(set)集合類似於列表,但每個元素都必須是獨一無二的通過對包含重複元素的列表調用set() ,可讓Python找出列表中獨一無二的元素,並使用這些元素來創建一個集合

favorite_languages={
    'simth':'python',
    'bob':'c',
    'bill':'matlab',
    'marry':'python',
    }
print("The following languages have been mentioned:\n")
for language in set(favorite_languages.values()): # 使用 set
    print(language.title())

'''
The following languages have been mentioned:

Python
C
Matlab
'''

嵌套

將一系列字典存儲在列表中,或將列表作爲值存儲在字典中,這稱爲嵌套 。你可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。

字典列表:在列表內存儲字典

創建:

people1 = {'姓名': '王小二', '年齡':18}
people2 = {'姓名':'張二麻子','年齡':17}
people3 = {'姓名':'李四','年齡':20}

peoples = [people1,people2,people3]

for people in peoples:
    print(people)
    
'''
{'姓名': '王小二', '年齡': 18}
{'姓名': '張二麻子', '年齡': 17}
{'姓名': '李四', '年齡': 20}
'''

對字典列表的操作與對列表、字典的操作相同。

在字典中存儲列表

程序中languages返回一個列表

favorite_languages={
   'simth':['python','c'],
   'bob':'c',
   'bill':['matlab','java'],
   'marry':['r','java','c++']
   }

for name,languages in favorite_languages.items():
   if len(languages)==1:
       print("\n"+name.title()+"'s favorite language is:"+languages.title())
   else:
       print("\n"+name.title()+"'s favorite language are:")
       for language in languages:
           print("\t"+language.title())

for name,languages in favorite_languages.items():
   for language in languages:
       print("\n"+name.title()+"'s favorite language is(are):"+language)
        
'''
Simth's favorite language are:
	Python
	C

Bob's favorite language is:C

Bill's favorite language are:
	Matlab
	Java

Marry's favorite language are:
	R
	Java
	C++

Simth's favorite language is(are):python

Simth's favorite language is(are):c

Bob's favorite language is(are):c

Bill's favorite language is(are):matlab

Bill's favorite language is(are):java

Marry's favorite language is(are):r

Marry's favorite language is(are):java

Marry's favorite language is(are):c++
'''

在字典中存儲字典

例1:

cities={
    '北京':{
        '國家':'中國',
        '人口':'500萬',
        '歷史':'明清兩代首都',
        },
    '華盛頓':{
        '國家':'美國',
        '人口':'400萬',
        '歷史':'美國首都',
        },
        }

for city,value in cities.items():
    print("\n城市:"+city)
#    print("\t國家:"+value['國家'])
#    print("\t人口:"+value['人口'])
#    print("\t歷史:"+value['歷史'])
    for k,v in value.items():
       print("\t"+k+':'+v)
      
'''
城市:北京
		國家:中國
		人口:500萬
		歷史:明清兩代首都

城市:華盛頓
		國家:美國
		人口:400萬
		歷史:美國首都
'''

例2:

users={
  '001':{
      'fast name':'erxiao',
      'last name':'wang',
      'location':'beijing',
      },
  '002':{
      'fast name':'emma',
      'last name':'smith',
      'location':'new york',
      },
          
  }
for user_id,user_info in users.items():
   print('\nUser ID:'+user_id)
   
   full_name=user_info['last name'].title()+" "+user_info['fast name'].title()
   print("\tFull name:"+full_name)
   print("\tLocation:"+user_info['location'].title())
   
   #print("\t"+full_name+':'+value['location'].title())

'''
User ID:001
	Full name:Wang Erxiao
	Location:Beijing

User ID:002
	Full name:Smith Emma
	Location:New York
'''
\nUser ID:'+user_id)
   
   full_name=user_info['last name'].title()+" "+user_info['fast name'].title()
   print("\tFull name:"+full_name)
   print("\tLocation:"+user_info['location'].title())
   
   #print("\t"+full_name+':'+value['location'].title())

'''
User ID:001
	Full name:Wang Erxiao
	Location:Beijing

User ID:002
	Full name:Smith Emma
	Location:New York
'''
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章