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

Common methods of dictionary and traversal in Python

編輯:Python

Preface :

The dictionary is based on “ key — value ” For stored unordered data sets .“ key — value ” Yes, it's a dictionary element , Access the elements in it with “ key ” To visit . The key of the dictionary can be a string 、 Integers 、 Tuple or dictionary . The value of the dictionary can also be a string 、 Integers .

The list cannot be used as a key to the dictionary , Because the list is variable . In the same dictionary , The same key only appears once , It is an index to access other data . If you assign a key repeatedly , The later assigned value will overwrite the previous value . The list can be used as the value of the dictionary .

Common dictionary methods :

x.keys(),x.values(),x.items() All need parentheses , The three are used in very similar ways , Let's talk about it below x.keys() Mainly .

x = {' Zhang San ': 86, ' Zhao si ': 76, ' Li Gang ': 65, ' Wang Wu ': 80, ' Wu Liu ': 99, ' Qian Qi ': 50}print(x.keys())print(x.keys)

The return result is :

dict_keys([' Zhang San ', ' Zhao si ', ' Li Gang ', ' Wang Wu ', ' Wu Liu ', ' Qian Qi '])
<built-in method keys of dict object at 0x0000013DC56A7BD0>

although x.keys Can run successfully , But this is not what we want .

use x.keys(),x.values(),x.items() Method to get the elements in the dictionary , The types returned by these three methods are :

dict_keys

dict_values

dcit_items

All three types can be converted into list types , Its members can then be accessed by index or slice .

x = {' Zhang San ': 86, ' Zhao si ': 76, ' Li Gang ': 65, ' Wang Wu ': 80, ' Wu Liu ': 99, ' Qian Qi ': 50}y = list(x.keys())print(y)for i in y:    print(i)

Use list() Just convert it to list type

[' Zhang San ', ' Zhao si ', ' Li Gang ', ' Wang Wu ', ' Wu Liu ', ' Qian Qi ']
however , If you think this traversal is too troublesome , The following methods can be used ( The steps of converting data types are omitted ).

x = {' Zhang San ': 86, ' Zhao si ': 76, ' Li Gang ': 65, ' Wang Wu ': 80, ' Wu Liu ': 99, ' Qian Qi ': 50}for i in x.keys():    print(i)

Next, let's look at an example :

example : A dictionary stores a person's name and several city names that the person likes , Go through the dictionary , Print the city everyone likes in the dictionary .

The dictionary is as follows :

a = {' Zhao Yi ': [' Beijing ', ' Shanghai '], ' Qian Er ': [' Hangzhou ', ' ningbo ', ' Xi'an '],     ' Sun San ': [' shaoxing ', ' changchun '], ' Li Si ': [' Beijing '], ' Friday ': [' ningbo ', ' Xi'an ', ' urumqi '], ' Wu Liu ': [' urumqi ']}

The results to be displayed are as follows :

Zhao Yi's favorite cities are : Beijing , Shanghai
Qian Er's favorite cities are : Hangzhou , ningbo , Xi'an
Sun San's favorite cities are : shaoxing , changchun
Li Si's favorite cities are : Beijing
Favorite cities on Friday are : ningbo , Xi'an , urumqi
Wu Liu's favorite cities are : urumqi

The code is as follows :

a = {' Zhao Yi ': [' Beijing ', ' Shanghai '], ' Qian Er ': [' Hangzhou ', ' ningbo ', ' Xi'an '],     ' Sun San ': [' shaoxing ', ' changchun '], ' Li Si ': [' Beijing '], ' Friday ': [' ningbo ', ' Xi'an ', ' urumqi '], ' Wu Liu ': [' urumqi ']}for k in a.keys():    print(k, end="")    print(' Favorite cities are :', end="")    # City list length     b = len(a[k])    for i in range(b):        if i < b-1:            # a[k][i] It's the second in his favorite city i individual             print(a[k][i], end=",")        else:            # There should be a new line after the last city name             print(a[k][i])

analysis : First a It's a dictionary , Where the value is a list , So we need to find the key first , Then traverse the value corresponding to the key ( list ) Content , One by one . We need two for loop , The key to traverse the dictionary for the first time , Traverse the contents of the list for the second time . In the code a[k][i] This function is realized .

print(k, end="")print(' Favorite cities are :', end="")

If it's too much trouble , You can change the code to use format() function

print('{} Favorite cities are :'.format(k), end="")

in addition :

Here are x.keys(),x.values(),x.items() Some of the code for , If necessary, you can use

x = {' Zhang San ': 86, ' Zhao si ': 76, ' Li Gang ': 65, ' Wang Wu ': 80, ' Wu Liu ': 99, ' Qian Qi ': 50}# 1print(x.keys())y = list(x.keys())print(y)for i in y:    print(i)for i in x.keys():    print(i)# 2print(x.values())y = list(x.values())print(y)for i in x.values():    print(i)# 3print(x.items())y = list(x.items())print(y)for i in x.items():    print(i)

This is about python This is the end of the article on dictionary and common methods of traversal , More about python Please search the previous articles of the software development network or continue to browse the following related articles. I hope you will support the software development network in the future !



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