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

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

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]。通过list类将字典转换为一个键的列表,并通过访问索引-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()编写了一段代码,用于仅找出字典的第一个元素。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程