在 Python 中的迴圈內將鍵值對新增到字典中

Vaibhav Vaibhav 2022年5月17日
在 Python 中的迴圈內將鍵值對新增到字典中

字典是一種神奇而高效的資料結構,可以在 Python 中以鍵值對的形式儲存資料。

由於它是一種資料結構,字典不僅特定於 Python,還可以用於其他程式語言,如 C++、Java、JavaScript 等。它被稱為不同的名稱,如 map 和 JSON(JavaScript Object Notation)目的。

字典有一個鍵,鍵可以是任何可雜湊且不可變的值或物件。這兩個要求背後的原因是物件的雜湊表示取決於它儲存在其中的值。

如果可以隨時間操作這些值,則該物件將不具有唯一且固定的雜湊表示。字典中的值可以是任何東西;它可以是整數值、浮點值、雙精度值、字串值、類物件、列表、二叉樹、連結串列、函式,甚至是字典。

就時間複雜度而言,字典平均需要常數時間 O(1) 來新增、刪除和訪問元素。

本文將討論如何在迴圈內將鍵值對新增到字典中。

將鍵值對新增到迴圈內的字典

要將鍵值對新增到迴圈內的字典中,我們可以建立兩個列表來儲存字典的鍵和值。接下來,假設 ith 鍵用於 ith 值,我們可以一起迭代兩個列表,並將值新增到字典中的相應鍵中。

讓我們藉助一些 Python 程式碼來理解這一點,參考以下程式碼:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
def add(*args):
    s = 0
    
    for x in args:
        s += x
        
    return s

dictionary = {}
keys = [
    "Integer", 
    "String", 
    "Float", 
    "List of Strings", 
    "List of Float Numbers", 
    "List of Integers", 
    "Dictionary", 
    "Class Object", 
    "Function", 
    "List of Class Objects"
]
values = [
    1, 
    "Hello", 
    2.567, 
    ["Computer", "Science"], 
    [1.235, 5.253, 77.425], 
    [11, 22, 33, 44, 55], 
    {"a": 500, "b": 1000, "c": 1500}, 
    Point(1, 6), 
    add, 
    [Point(0, 0), Point(0, 7.5), Point(7.5, 7.5), Point(7.5, 0)]
]

for key, value in zip(keys, values):
    dictionary[key] = value

print(dictionary)

輸出:

{'Integer': 1, 'String': 'Hello', 'Float': 2.567, 'List of Strings': ['Computer', 'Science'], 'List of Float Numbers': [1.235, 5.253, 77.425], 'List of Integers': [11, 22, 33, 44, 55], 'Dictionary': {'a': 500, 'b': 1000, 'c': 1500}, 'Class Object': <__main__.Point object at 0x7f2c74906d90>, 'Function': <function add at 0x7f2c748a3d30>, 'List of Class Objects': [<__main__.Point object at 0x7f2c749608b0>, <__main__.Point object at 0x7f2c748a50a0>, <__main__.Point object at 0x7f2c748a5430>, <__main__.Point object at 0x7f2c748a53d0>]}

上述解決方案的時間複雜度為 O(n),上述解決方案的空間複雜度也是 O(n),其中 nkeysvalues 列表的大小。此外,上面的程式碼描述了我們談到的所有型別的值都可以儲存在字典中。

我們可以通過重新迭代字典並列印每個鍵值對或在將它們新增到字典的同時列印每個鍵值對來美化輸出。請注意,你還可以使用預先構建的 Python 包,例如 json 包和外部開源包來處理 JSON 輸出、新增顏色編碼、新增縮排等。

對於我們的用例,我們將建立一個用於列印字典的存根函式。參考以下程式碼:

def print_dictionary(dictionary):
    for key, value in dictionary.items():
        print(f"{key}: {value}")

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
def add(*args):
    s = 0
    
    for x in args:
        s += x
        
    return s

dictionary = {}
keys = [
    "Integer", 
    "String", 
    "Float", 
    "List of Strings", 
    "List of Float Numbers", 
    "List of Integers", 
    "Dictionary", 
    "Class Object", 
    "Function", 
    "List of Class Objects"
]
values = [
    1, 
    "Hello", 
    2.567, 
    ["Computer", "Science"], 
    [1.235, 5.253, 77.425], 
    [11, 22, 33, 44, 55], 
    {"a": 500, "b": 1000, "c": 1500}, 
    Point(1, 6), 
    add, 
    [Point(0, 0), Point(0, 7.5), Point(7.5, 7.5), Point(7.5, 0)]
]

for key, value in zip(keys, values):
    dictionary[key] = value

print_dictionary(dictionary)

輸出:

Integer: 1
String: Hello
Float: 2.567
List of Strings: ['Computer', 'Science']
List of Float Numbers: [1.235, 5.253, 77.425]
List of Integers: [11, 22, 33, 44, 55]
Dictionary: {'a': 500, 'b': 1000, 'c': 1500}
Class Object: <__main__.Point object at 0x7f7d94160d90>
Function: <function add at 0x7f7d940fddc0>
List of Class Objects: [<__main__.Point object at 0x7f7d941ba8b0>, <__main__.Point object at 0x7f7d940ff130>, <__main__.Point object at 0x7f7d940ff310>, <__main__.Point object at 0x7f7d940ff3d0>]

上述解決方案的時間和空間複雜度與前一個解決方案的 O(n) 相同。

上面的兩個程式碼片段使用了一個 for 迴圈。我們可以使用 while 迴圈執行相同的任務。

以下程式碼片段描述了使用 while 迴圈向字典新增值。

def print_dictionary(dictionary):
    for key, value in dictionary.items():
        print(f"{key}: {value}")

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
def add(*args):
    s = 0
    
    for x in args:
        s += x
        
    return s

dictionary = {}
keys = [
    "Integer", 
    "String", 
    "Float", 
    "List of Strings", 
    "List of Float Numbers", 
    "List of Integers", 
    "Dictionary", 
    "Class Object", 
    "Function", 
    "List of Class Objects"
]
values = [
    1, 
    "Hello", 
    2.567, 
    ["Computer", "Science"], 
    [1.235, 5.253, 77.425], 
    [11, 22, 33, 44, 55], 
    {"a": 500, "b": 1000, "c": 1500}, 
    Point(1, 6), 
    add, 
    [Point(0, 0), Point(0, 7.5), Point(7.5, 7.5), Point(7.5, 0)]
]
n = min(len(keys), len(values))
i = 0

while (i != n):
    dictionary[keys[i]] = values[i]
    i += 1

print_dictionary(dictionary)

輸出:

Integer: 1
String: Hello
Float: 2.567
List of Strings: ['Computer', 'Science']
List of Float Numbers: [1.235, 5.253, 77.425]
List of Integers: [11, 22, 33, 44, 55]
Dictionary: {'a': 500, 'b': 1000, 'c': 1500}
Class Object: <__main__.Point object at 0x7fdbe16c0d90>
Function: <function add at 0x7fdbe165ddc0>
List of Class Objects: [<__main__.Point object at 0x7fdbe171a8b0>, <__main__.Point object at 0x7fdbe165f130>, <__main__.Point object at 0x7fdbe165f310>, <__main__.Point object at 0x7fdbe165f3d0>]

上述解決方案的時間和空間複雜度與前一個解決方案的 O(n) 相同。

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

相關文章 - Python Dictionary