首页 > 文章列表 > 获取字典中的第一个和最后一个元素的Python程序

获取字典中的第一个和最后一个元素的Python程序

字典 第一个元素 最后一个元素
189 2023-09-06

Python是一种解释型的、面向对象的、高级的编程语言,具有动态语义。由Gudio Van Rossum于1991年开发。它支持多种编程范式,包括结构化、面向对象和函数式编程。在深入讨论这个主题之前,让我们先复习一下与我们提供的问题相关的基本概念。

字典是一组独特、可变且有序的项。在字典的书写中使用花括号,并且它们包含键和值:键名可以用来引用字典对象。数据值以键:值对的形式保存在字典中。

有序和无序含义

当我们说字典是有序的时,我们是指其内容具有一定的顺序,不会改变。无序的项目缺乏明确的顺序,因此无法使用索引来找到特定的项目。

示例

请参阅以下示例以更好地理解上面讨论的概念。

请注意,字典键是区分大小写的;具有相同名称但大小写不同的键将被处理成不同的情况。

Dict_2 = {1: 'Ordered', 2: 'And', 3: 'Unordered'}
print (Dict_2)

输出

{1: 'Ordered', 2: 'And', 3: 'Unordered'}

示例

查看以下示例以更好地理解该概念

Primary_Dict = {1: 'Grapes', 2: 'are', 3: 'sour'}
print("nDictionary with the use of Integer Keys is as following: ")
print(Primary_Dict)

# Creating a Dictionary

# with Mixed keys
Primary_Dict = {'Fruit': 'Grape', 1: [10, 22, 13, 64]}
print("nDicionary with the use of Mixed Keys is as following: ")
print(Primary_Dict)

输出

Dictionary with the use of Integer Keys is as following:
{1: 'Grapes', 2: 'are', 3: 'sour'}
Dictionary with the use of Mixed Keys:
{'Fruit': 'Grape', 1: [10, 22, 13, 64]}

在使用Python时,有许多情况下我们需要获取字典的主键。它可以用于许多不同的具体用途,比如测试索引或其他类似的用途。让我们来介绍一些完成这项工作的方法。

使用list()类 + keys()

可以使用上述技术的组合来执行此特定任务。在这里,我们只是根据keys()从完整字典中收集的键创建一个列表,然后仅访问第一个条目。在使用它之前您只需要考虑一个因素,即它的复杂性。通过迭代字典中的每个项目,它首先将整个字典转换为列表,然后提取其第一个成员。这种方法的复杂度是O.(n)。

使用list()类获取字典中的最终键,如last key = list(my dict)[-1]。字典通过列表类转换为键列表,通过访问索引-1处的元素可以获得最后一个键。

示例

请参阅以下示例以更好地理解

primary_dict = {
   'Name': 'Akash',
   'Rollnum': '3',
   'Subj': 'Bio'
}
last_key = list(primary_dict) [-1]
print (" last_key:" + str(last_key))
print(primary_dict[last_key])
first_key = list(primary_dict)[0]
print ("first_key :" + str(first_key))

输出

last_key: Subj
Bio
first_key :Name

示例

以下程序创建了一个名为Primary_dict的字典,其中包含五对键值对。然后将整个字典打印到屏幕上,接着分别打印出字典的第一个和最后一个键。

primary_dict = {'Grapes' : 1, 'are' : 2, 'sour' : 3, 'and' : 4, 'sweet' : 5}
print ("The primary dictionary is : " + str(primary_dict))
res1 = list (primary_dict.keys())[0]
res2 = list (primary_dict.keys())[4]
print ("The first key of the dictionary is : " + str(res1))
print ("the last key of the dictionary is :" + str(res2))

输出

The primary dictionary is : {'Grapes': 1, 'are': 2, 'sour': 3, 'and': 4, 'sweet': 5}
The first key of the dictionary is : Grapes
the last key of the dictionary is : sweet

示例

如果您只需要字典的第一个键,获取它的有效方法是使用“next()”和“iter()”函数的组合。 iter() 函数用于将字典条目转换为可迭代对象,而 next() 则获取第一个键。这种方法的复杂度为 O(1)。请参阅以下示例以更好地理解。

primary_dict = {'Grapes' : 1, 'are' : 2, 'sour' : 3, 'and' : 4, 'sweet' : 5}
print ("The primary dictionary is : " + str(primary_dict))
res1 = next(iter(primary_dict))
print ("The first key of dictionary is as following : " + str(res1))

输出

The primary dictionary is : {'Grapes': 1, 'are': 2, 'sour': 3, 'and': 4, 'sweet': 5}
The first key of dictionary is as following : Grapes

结论

在本文中,我们解释了从字典中查找第一个和最后一个元素的两个不同示例。我们还编写了一个代码,通过使用 next()+ iter() 来仅查找字典的第一个元素。