[python] Summary of dictionary creation methods


   There are many ways to create dictionaries in python, which can be roughly divided into the following three categories according to the value transfer method:

1. Direct value transfer

Import data directly into the dictionary:

d1 = dict(Alice=31, Bob=24, Cindy=27)
d2 = {
    
    "Alice": 31, "Bob": 24, "Cindy": 27}
d3 = dict({
    
    "Alice": 31, "Bob": 24, "Cindy": 27})

2. Pass in the key list and value list

Known key and value information:

names = ["Alice", "Bob", "Cindy"]
ages = [31, 24, 27]

Import the key and value lists into the dictionary respectively:

d4 = {
    
    names[i]: ages[i] for i in range(len(names))}
d5 = {
    
    z[0]: z[1] for z in zip(names, ages)}
d6 = {
    
    k: v for (k, v) in zip(names, ages)}

3. Pass in a list of key-value pair tuples

Known key-value pair information:

persons = [("Alice", 31), ("Bob", 24), ("Cindy", 27)]

Import a list of key-value tuples into a dictionary:

d7 = {
    
    p[0]: p[1] for p in persons}
d8 = {
    
    k: v for (k, v) in persons}

Output:

>>> d1 == d2 == d3 == d4 == d5 == d6 == d7 == d8
True

Recommended reading:
[python] Use of generative expressions

For more usage methods and applications of python, please pay attention to subsequent updates~

おすすめ

転載: blog.csdn.net/weixin_44844635/article/details/131382593
おすすめ