Python 中的字典是键值的集合,用于像地图一样存储数据值,这与其他仅将单个值作为元素的数据类型不同。
字典包含键:值对。字典中提供了Key-Value,使其更加优化。
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(Dict)
输出:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
在Python中,可以通过将一系列元素放置在大括号{}内并以“逗号”分隔来创建字典。Dictionary 包含成对的值,一个是 Key,另一个对应的成对元素是它的Key:value。字典中的值可以是任何数据类型并且可以重复,而键不能重复并且必须是不可变的。
注意 –字典键是区分大小写的,相同名称但不同大小写的键将被区别对待。
# Creating a Dictionary # with Integer Keys Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\nDictionary with the use of Integer Keys: ") print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\nDictionary with the use of Mixed Keys: ") print(Dict)
Dictionary with the use of Integer Keys: {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with the use of Mixed Keys: {'Name': 'Geeks', 1: [1, 2, 3, 4]}
字典也可以通过内置函数 dict() 创建。只需放置到花括号{} 即可创建一个空字典。
# Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with dict() method Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'}) print("\nDictionary with the use of dict(): ") print(Dict) # Creating a Dictionary # with each item as a Pair Dict = dict([(1, 'Geeks'), (2, 'For')]) print("\nDictionary with each item as a pair: ") print(Dict)
Empty Dictionary: {} Dictionary with the use of dict(): {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with each item as a pair: {1: 'Geeks', 2: 'For'}
时间复杂度: O(len(dict)) 空间复杂度: O(n)
时间复杂度: O(len(dict))
空间复杂度: O(n)
# Creating a Nested Dictionary # as shown in the below image Dict = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}} print(Dict)
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
可以通过多种方式添加元素。通过定义值和键,例如 Dict[Key] = 'Value',一次可以将一个值添加到字典中。可以使用内置的update()方法更新字典中的现有值。嵌套键值也可以添加到现有词典中。
注意 -添加值时,如果键值已经存在,则该值将被更新,否则会将具有该值的新键添加到字典中。
# Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Adding elements one at a time Dict[0] = 'Geeks' Dict[2] = 'For' Dict[3] = 1 print("\nDictionary after adding 3 elements: ") print(Dict) # Adding set of values # to a single Key Dict['Value_set'] = 2, 3, 4 print("\nDictionary after adding 3 elements: ") print(Dict) # Updating existing Key's Value Dict[2] = 'Welcome' print("\nUpdated key value: ") print(Dict) # Adding Nested Key value to Dictionary Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}} print("\nAdding a Nested Key: ") print(Dict)
Empty Dictionary: {} Dictionary after adding 3 elements: {0: 'Geeks', 2: 'For', 3: 1} Dictionary after adding 3 elements: {0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)} Updated key value: {0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)} Adding a Nested Key: {0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}}
时间复杂度: O(1)/O(n)
空间复杂度: O(1)
为了访问字典的项目,请参考其键名。键可以在方括号内使用。
# Python program to demonstrate # accessing a element from a Dictionary # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using key print("Accessing a element using key:") print(Dict['name']) # accessing a element using key print("Accessing a element using key:") print(Dict[1])
Accessing a element using key: For Accessing a element using key: Geeks
还有一个名为get()的方法也有助于从字典中访问元素。此方法接受键作为参数并返回值。
时间复杂度: O(1)
# Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # accessing a element using get() # method print("Accessing a element using get:") print(Dict.get(3))
Accessing a element using get: Geeks
为了访问嵌套字典中任何键的值,请使用索引 [] 语法。
# Creating a Dictionary Dict = {'Dict1': {1: 'Geeks'}, 'Dict2': {'Name': 'For'}} # Accessing element using key print(Dict['Dict1']) print(Dict['Dict1'][1]) print(Dict['Dict2']['Name'])
{1: 'Geeks'} Geeks For
可以使用 del 关键字删除字典的项目,如下所示。
# Python program to demonstrate # Deleting Elements using del Keyword # Creating a Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} print("Dictionary =") print(Dict) #Deleting some of the Dictionar data del(Dict[1]) print("Data after deletion Dictionary=") print(Dict)
输出
Dictionary ={1: 'Geeks', 'name': 'For', 3: 'Geeks'} Data after deletion Dictionary={'name': 'For', 3: 'Geeks'}
# demo for all dictionary methods dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"} # copy() method dict2 = dict1.copy() print(dict2) # clear() method dict1.clear() print(dict1) # get() method print(dict2.get(1)) # items() method print(dict2.items()) # keys() method print(dict2.keys()) # pop() method dict2.pop(4) print(dict2) # popitem() method dict2.popitem() print(dict2) # update() method dict2.update({3: "Scala"}) print(dict2) # values() method print(dict2.values())
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'} {} Python dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')]) dict_keys([1, 2, 3, 4]) {1: 'Python', 2: 'Java', 3: 'Ruby'} {1: 'Python', 2: 'Java'} {1: 'Python', 2: 'Java', 3: 'Scala'} dict_values(['Python', 'Java', 'Scala'])
原文链接:codingdict.net