SoFunction
Updated on 2024-10-30

How Python reads all key-value pairs of a dictionary

If there are some values stored in the dictionary, what should I do if I want to take them out?

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

To retrieve all the key-value pairs in a dictionary, you can use items() to return a list of key-value pairs and iterate through them in a for loop.

#Create a storage for a student's information, by traversing it you can take out all the information
student={'name':'xiaoming','age':11,'school':'tsinghua'}
for key,value in ():
    print(key+':'+str(value))

Output:

age:11

name:xiaoming

school:tsinghua

Attention:

The traversed return values are not output in the same order as they are stored, and the order of output changes each time

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

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

You can use the keys() method to take out the keys in the dictionary without taking the corresponding values

# Create a dictionary of people and corresponding favorite fruits
people={'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'}
for name in ():
    print(name)

Output: (order is randomized)

hanmeimie

gaolan

fanming

lifei

Note: the keys() method returns a list, think in terms of lists!

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

# Create a dictionary of people and corresponding favorite fruits
people={'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'}
for name in sorted(()):
    print(name)

Output:

fanming

gaolan

hanmeimie

lifei

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

You can use values() to retrieve values from a dictionary.

# Create a dictionary of people and corresponding favorite fruits
people={'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'}
for fruit in ():
    print(fruit)

Output:

peach

banana

peach

apple

Note that there is no duplicate value in the output above, if I want to remove the duplicate value how to do it, you can use the set set() to remove duplicate values

# Create a dictionary of people and corresponding favorite fruits
people={'lifei':'apple','fanming':'peach','gaolan':'banana','hanmeimie':'peach'}
for fruit in set(()):
    print(fruit)

Output:

apple

peach

banana

practice

Create a list of people, some of whom are in the Fruit Dictionary (following on from the Favorite Fruit Dictionary above) and some of whom are not, and for those who have already explicitly liked the fruit, ask if there are any other fruits needed, and for those who haven't explicitly liked the fruit, invite the person to name one of the fruits they like.

# Create a dictionary of people and corresponding favorite fruits
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 one of your favorite fruits?')

Output:

Can you tell me one of your favorite fruits?

Can you tell me one of your favorite fruits?

Do you need other fruits?

Do you need other fruits?

summarize

It's been a long morning. It took a lot of effort to finish this section.

1, first traversing the dictionary all the key-value pairs can be used items()

2, only traversing the key when you can use key (), you can also use sorted () sorting

3, only traversing the value, you can use values (), you can also use set () to remove duplicates in the value of values

Supplementary: python fetch a dictionary key or value / how to delete a dictionary key-value pair / how to iterate through a dictionary

Define a dictionary and initialize it directly.

my_dict = dict(name="lowman", age=45, money=998, hourse=None)

1. Take out all the keys of the dictionary

key_list = my_dict.keys() returns the 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']

Another way to get all the keys out of a dictionary is to use the built-in function set(), which converts it to a set data structure. A set, in fact, can be thought of as a dictionary with only keys.

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

Output.

{'age', 'name'}

Note that this outputs the collection type

2. Take out all the values of the dictionary

value_list = my_dict.values() returns the 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 python2, these two methods return a list, but in python3, they return an iterator. If you want to get the element you need by subscripting it directly, you can use the list() method to convert it to a list first, and then fetch the value.

3. Remove the value of a dictionary key

value = my_dict["key"] This will throw an exception if the key is not present.

4. Safely take out the value of a dictionary key

This returns None if the key is not present: value = my_dict.get("key")

It is also possible to customize a default value to return: value = my_dict.get("key", default value)

5. Iterate over the dictionary

for item in my_dict:
    print(item)

Output:

name

hourse

money

age

Fetch is the key of the dictionary

6. comes with a method items() that 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) # If you take a value like this, 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"]

This removes the entire key-value pair

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.