在 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)
,其中 n
是 keys
和 values
列表的大小。此外,上面的代码描述了我们谈到的所有类型的值都可以存储在字典中。
我们可以通过重新迭代字典并打印每个键值对或在将它们添加到字典的同时打印每个键值对来美化输出。请注意,你还可以使用预先构建的 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)
相同。