创建 Python 字典的正确语法是什么?

programmingpythonserver side programming

创建 Python 字典的正确语法是以键:值对的形式存储值。在冒号左侧,我们存储键,在右侧存储值,即

键:值

字典用花括号括起来,不允许重复。根据 3.7 Python 更新,字典现在是有序的。将字典视为一组键:值对,要求键是唯一的(在一个字典内)。字典中的每个键与其值都用冒号 (:) 分隔,项之间用逗号分隔,整个字典用花括号括起来。

使用 Python 创建包含 4 个键值对的字典

我们将创建 4 个键值对,键为 Product、Model、UnitsAvailable,值是 Mobile、XUT、120Yes。键位于冒号左侧,而值位于右侧 −

示例

# Creating a Dictionary with 4 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" } # Displaying the Dictionary print("Dictionary = \n",myprod)

输出

Dictionary =
 {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}

以上,我们以包含 4 个键值对的字典形式显示了产品详细信息。

使用 Python 创建包含 5 个键值对的字典

我们将创建 5 个键值对,其键为 Product、Model、Units、Available、Grades,值 Mobile、XUT、120、Yes、"A"

示例

# Creating a Dictionary with 5 key-value pairs myprod = { "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes", "Grades": "A" } # Displaying the Dictionary print("Dictionary = \n",myprod)

输出

Dictionary =
 {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes', 'Grades': 'A'}

以上,我们以包含 5 个键值对的字典形式显示了产品详细信息。

使用 dict() 方法在 Python 中创建字典

我们还可以使用内置方法 dict() 创建字典。我们在方法本身中设置了键值对 −

示例

# Creating a Dictionary using the dict() method myprod = dict({ "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" }) # Displaying the Dictionary print("Dictionary = \n",myprod) # Display the Keys print("\nKeys = ",myprod.keys()) # Display the Values print("Values = ",myprod.values())

输出

Dictionary = 
 {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}

Keys =  dict_keys(['Product', 'Model', 'Units', 'Available'])
Values =  dict_values(['Mobile', 'XUT', 120, 'Yes'])

相关文章