Python learning road 5-dictionary

This series is a compilation of notes for the introductory book "Python Programming: From Getting Started to Practice", which belongs to the primary content. The title sequence follows the title of the book.
This chapter mainly introduces the concept of dictionary, basic operations and some advanced operations.

Using a dictionary (Dict)

In Python, a dictionary is a sequence of key-value pairs. Each key is associated with a value, and the key is used to access the value. In Python, curly braces {}are used to denote dictionaries.

# 代码:
alien = {"color": "green", "points": 5}

print(alien)  # 输出字典
print(alien["color"])   # 输出键所对应的值
print(alien["points"])

# 结果:
{'color': 'green', 'points': 5}
green
5

A dictionary can contain any number of key-value pairs, and a dictionary in Python is a dynamic structure to which key-value pairs can be added at any time.

# 代码:
alien = {"color": "green", "points": 5}
print(alien)

alien["x_position"] = 0
alien["y_position"] = 25
print(alien)

# 结果:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

Sometimes adding key-value pairs to an empty dictionary is a convenience, and other times it is necessary, such as when using a dictionary to store user-supplied data or when writing code that automatically generates a large number of key-value pairs, this is often the case To define an empty dictionary first.

# 代码:
alien = {}    # 定义空字典的语法
alien["x_position"] = 0
alien["y_position"] = 25
print(alien)

# 结果:
{'x_position': 0, 'y_position': 25}

If you want to modify the value in the dictionary, just access it by key name.

# 代码:
alien = {"color" : "green"}
print("The alien is " + alien["color"] + ".")

alien["color"] = "yellow"
print("The alien is now " + alien["color"] + ".")

# 结果:
The alien is green.
The alien is now yellow.

For information that is no longer needed in the dictionary, delthe corresponding key-value pair can be deleted with the statement:

# 代码:
alien = {"color": "green", "points": 5}
print(alien)

del alien["color"]
print(alien)

# 结果:
{'color': 'green', 'points': 5}
{'points': 5}

In the previous examples, various information of an object constitute a dictionary (alien information in the game). The dictionary can also be used to store unified information of many objects:

favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",   # 建议在最后一项后面也加个逗号,便于之后添加元素
}

iterate over the dictionary

Iterate over all key-value pairs

# 代码:
user_0 = {
    "username": "efermi",
    "first": "enrico",
    "last": "fermi",
}

for key, value in user_0.items():
    print("Key: " + key)
    print("Value: " + value + "\n")

# 结果:
Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi

One thing to note here is that when traversing a dictionary, the return order of key-value pairs is not necessarily the same as the storage order. Python does not care about the storage order of key-value pairs, but only tracks the association between keys and values.

iterate over all keys in dictionary

The dictionary method keys()returns all the keys in the dictionary as a list . The following code iterates over all the keys in the dictionary:

# 代码:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

for name in favorite_languages.keys():
    print(name.title())

# 结果:
Jen
Sarah
Edward
Phil

It is also possible to iterate over all keys of a dictionary as follows:

# 代码:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

for name in favorite_languages:
    print(name.title())

# 结果:
Jen
Sarah
Edward
Phil

But traversal with methods keys()is more explicit.
You can also use the keys()method to determine whether a key is in the dictionary:

# 代码:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

if "erin" not in favorite_languages.keys():
    print("Erin, please take our poll!")

# 结果:
Erin, please take our poll!

Use a sorted()function to iterate over all keys in a dictionary in order:

# 代码:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for taking the poll.")

# 结果:
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

iterate over all values ​​in dictionary

Similar to traversing all keys using keys()methods, traversing all values ​​using values()methods

# 代码:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language.title())

# 结果:
Python
C
Ruby
Python

It can be seen from the results that the above code does not consider the problem of deduplication. If you want to deduplicate, you can call set():

# 代码:
favorite_languages = {
    "jen": "python",
    "sarah": "c",
    "edward": "ruby",
    "phil": "python",
}

print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())

# 结果:
Python
C
Ruby

nested

list of dictionaries

Taking the previous aliens as an example, three aliens form a list:

# 代码:
alien_0 = {"color": "green", "points": 5}
alien_1 = {"color": "yellow", "points": 10}
alien_2 = {"color": "red", "points": 15}

aliens = [alien_0, alien_1, alien_2]

for alien in aliens:
    print(alien)

# 结果:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

store list in dictionary

Whenever you need to associate a key to multiple values ​​in a dictionary, you can nest a list in the dictionary:

# 代码:
pizza = {
    "crust": "thick",
    "toppings": ["mushrooms", "extra cheese"],
}

print("You ordered a " + pizza["crust"] + "-crust pizza" +
      "with the following toppings:")

for topping in pizza["toppings"]:
    print("\t" + topping)

# 结果:
You ordered a thick-crust pizzawith the following toppings:
    mushrooms
    extra cheese

store dictionary in dictionary

When it comes to this case, the code will not be simple:

# 代码:
users = {
    "aeinstein": {
        "first": "albert",
        "last": "einstein",
        "location": "princeton",
    },
    "mcurie": {
        "first": "marie",
        "last": "curie",
        "location": "paris",
    },
}

for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info["first"] + " " + user_info["last"]
    location = user_info["location"]

    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())

# 结果:
Username: aeinstein
    Full name: Albert Einstein
    Location: Princeton

Username: mcurie
    Full name: Marie Curie
    Location: Paris

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325658058&siteId=291194637