search
HomeBackend DevelopmentPython TutorialPython program to get first and last element in dictionary

Python program to get first and last element in dictionary

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Developed by Gudio Van Rossum in 1991. It supports multiple programming paradigms, including structured, object-oriented, and functional programming. Before we dive into this topic, let's review the basic concepts relevant to the questions we provide.

A dictionary is a unique, mutable, and ordered set of items. Curly braces are used when writing dictionaries, and they contain keys and values: key names can be used to refer to dictionary objects. Data values ​​are stored in dictionaries in the form of key:value pairs.

The meaning of order and disorder

When we say that a dictionary is ordered, we mean that its contents have a certain order and will not change. Unordered items lack an explicit order, so the index cannot be used to find a specific item.

Example

See the following examples to better understand the concepts discussed above.

Please note that dictionary keys are case-sensitive; keys with the same name but different cases will be treated differently.

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

Output

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

Example

View the following examples to better understand the concept

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)

Output

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]}

When using Python, there are many situations where we need to obtain the primary key of the dictionary. It can be used for many different specific purposes, such as testing indexes or other similar purposes. Let's walk through some ways to get this done.

Use list() class keys()

A combination of the above techniques can be used to perform this specific task. Here we just create a list based on the keys collected from the complete dictionary with keys() and then access only the first entry. There is only one factor you need to consider before using it, its complexity. By iterating over each item in the dictionary, it first converts the entire dictionary to a list and then extracts its first member. The complexity of this method is O.(n).

Use the list() class to get the final key in the dictionary, such as last key = list(my dict)[-1]. The dictionary is converted into a list of keys via the list class, and the last key can be obtained by accessing the element at index -1.

Example

See the following examples for better understanding

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))

Output

last_key: Subj
Bio
first_key :Name

Example

The following program creates a dictionary named Primary_dict, which contains five key-value pairs. The entire dictionary is then printed to the screen, followed by the first and last keys of the dictionary.

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))

Output

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

Example

If you only need the first key of the dictionary, an efficient way to obtain it is to use a combination of the "next()" and "iter()" functions. The iter() function is used to convert the dictionary entry into an iterable object, while next() gets the first key. The complexity of this approach is O(1). See the following examples for better understanding.

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))

Output

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

in conclusion

In this article, we explained two different examples of finding the first and last element from a dictionary. We also wrote a code to find only the first element of the dictionary by using next() iter().

The above is the detailed content of Python program to get first and last element in dictionary. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor