Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to read all key-value pairs of dictionaries by Python

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how Python reads all the key-value pairs in the dictionary. It is very detailed and has a certain reference value. Friends who are interested must finish it!

1. I want to take out all the key-value pairs in the dictionary.

When you take out all the key-value pairs in the dictionary, you can use items () to return a list of key-value pairs and traverse with the for loop

# create an information to store a student. All the information can be retrieved by traversing student= {'name':'xiaoming','age':11,'school':'tsinghua'} for key,value in student.items (): print (key+':'+str (value))

Output:

Age:11

Name:xiaoming

School:tsinghua

Note:

The output and storage order of the traversal return values are different, and the output order will change each time.

The key and value variables in the for loop need to be separated by a comma','

2. I want to take out the keys in the dictionary

You can use the keys () method to extract the key from the dictionary without taking the corresponding value

# create a person and a dictionary that corresponds to people= {'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'} for name in people.keys (): print (name)

Output: (the order is random)

Hanmeimie

Gaolan

Fanming

Lifei

Note: the keys () method returns a list, and you should think about the problem in the same way as the list.

The order of the values returned by keys () is uncertain. If you want to sort them in order, you can use sorted () to sort them.

# create a person and a dictionary corresponding to fruit like people= {'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'} for name in sorted (people.keys ()): print (name)

Output:

Fanming

Gaolan

Hanmeimie

Lifei

3. I want to take out the values in the dictionary

You can use values () to fetch the values in the dictionary

# create a person and a dictionary that corresponds to people= {'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'} for fruit in people.values (): print (fruit)

Output:

Peach

Banana

Peach

Apple

Note that do you see any duplicate values in the output above? what if I want to remove the duplicate values? I can use the set set () to remove the duplicate values.

# create a person and a dictionary corresponding to fruit like people= {'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'} for fruit in set (people.values ()): print (fruit)

Output:

Apple

Peach

Banana

Practice

Create a list of people, some people are in the fruit dictionary (following the favorite fruit dictionary above), some people are not among them, for those who already clearly like fruit, ask if they need any other fruit, and for those who do not clearly like fruit, invite him to name a kind of fruit he likes.

# create a person and corresponding dictionary people_fruit= {'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimei':'peach'} people= [' lilei','caiming','hanmeimei','gaolan'] for name in people: if name in people_fruit.keys (): print ('do you need any other fruit?') Elif name not in people_fruit.keys (): print ('can you tell me what kind of fruit you like?')

Output:

Can you tell me a kind of fruit you like?

Can you tell me a kind of fruit you like?

Do you need any other fruit?

Do you need any other fruit?

Summary

There are a lot of things to do in the morning, and it took a lot of effort to finish this lesson.

1. First, you can use items () to traverse all the key-value pairs in the dictionary.

2. You can use key () when only traversing keys, and you can also use sorted () to sort.

3. When only traversing the value, you can use values (), and you can also use set () to remove duplicate values in the value.

Add: python takes out the key or value of the dictionary / how to delete the key-value pair of a dictionary / how to traverse the dictionary

First define a dictionary and initialize the assignment directly

My_dict = dict (name= "lowman", age=45, money=998, hourse=None) 1. Take out all the keys in the dictionary

Key_list = my_dict.keys () returns a list

My_dict = dict (name= "lowman", age=45, money=998, hourse=None) key_list = my_dict.keys () print (list (key_list))

Output:

['hourse',' name', 'age',' money']

There is another way to take out all the keys in the dictionary, which is to use the built-in function set () to convert it into a collection data structure. A collection can actually be understood as a dictionary with only keys:

Item = {"name": "lowman", "age": 27} data = set (item) print (data)

Output:

{'age',' name'}

Note that what is output is the collection type

two。 Take out all the values of the dictionary

Value_list = my_dict.values () returns a list

My_dict = dict (name= "lowman", age=45, money=998, hourse=None) value_list = my_dict.values () print (list (value_list))

Output:

[None, 45, 'lowman', 998]

Note: in the python2 environment, these two methods return a list, but in the python3 environment, they return an iterator. If you want to fetch the desired element directly through the subscript, you can convert it to a list and then take the value through the list () method.

3. Take out the value of a key in the dictionary

Value = my_dict ["key"] if you don't have this key, an exception will be thrown.

4. Safely take out the value of a key in the dictionary

If you don't have this key, return None:value = my_dict.get ("key").

You can also customize a default value to return: value = my_dict.get ("key", default)

5. Traversal dictionary for item in my_dict: print (item)

Output:

Name

Hourse

Money

Age

The key of the dictionary is taken out.

6. The built-in method items () can take out both the key and the value for key,value in my_dict.items (): print (key,value) for item in my_dict.items (): print (item) # so that it returns a tuple containing two elements, the first is the key and the second is the value

Output:

Hourse None

Money 998

Age 45

Name lowman

('hourse', None)

('money', 998)

('age', 45)

('name',' lowman')

7. Delete a dictionary key value pair my_dict = {"name": "lowman", "age": 12} del my_dict ["name"]

In this way, the whole key value pair is deleted.

The above is all the contents of the article "how to read all the key-value pairs in a dictionary by Python". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report