Python Create Dictionary with Integer
Last Updated :
28 Jan, 2025
The task of creating a dictionary from a list of keys in Python, where each key is assigned a unique integer value, involves transforming the list into a dictionary. Each element in the list becomes a key and the corresponding value is typically its index or a different integer.
For example, if we have a list like ['apple', 'banana', 'orange'], the goal is to convert it into a dictionary like {'apple': 0, 'banana': 1, 'orange': 2}, where each key is paired with a distinct integer.
Using dictionary comprehension
Dictionary comprehension is a efficient way to create dictionaries by iterating over an iterable. When used to create a dictionary with integers, we can pair each key with a unique integer, such as using the index of the element. This method is both readable and fast, making it one of the most Pythonic approaches for this task.
Python
li = ['apple', 'banana', 'orange']
d = {key: idx for idx, key in enumerate(li)}
print(d)
Output{'apple': 0, 'banana': 1, 'orange': 2}
Explanation: enumerate() generates index-value pairs from the list li , where the element is the key and its idx is the value. The dictionary comprehension then iterates over these pairs, creating a dictionary where each list element is mapped to its corresponding index.
Using dict(zip())
zip() pairs two iterables element-wise and when combined with dict(), it creates a dictionary. This method is particularly useful when we want to pair each element from a list with an index from a generated range. It’s an elegant solution for creating a dictionary with unique integer values as the keys.
Python
li = ['apple', 'banana', 'orange']
d = dict(zip(li, range(len(li))))
print(d)
Output{'apple': 0, 'banana': 1, 'orange': 2}
Explanation: zip() pairs each element of the list li with an index from range(len(li)) and dict() converts these pairs into a dictionary, mapping each element to its corresponding index.
Using enumerate
enumerate() yields both the index and the value from an iterable. By using enumerate() within a loop or comprehension, we can easily pair each key with a unique integer its index . This is a simple and efficient way to assign distinct integer values to dictionary keys.
Python
li = ['apple', 'banana', 'orange']
d = {} # initialized empty dictionary
for idx, key in enumerate(li):
d[key] = idx
print(d)
Output{'apple': 0, 'banana': 1, 'orange': 2}
Explanation: enumerate() generates index-value pairs and the for loop adds each pair to the empty dictionary d, mapping each element to its index.
Using map()
map() applies a given function to each item of an iterable. By combining map() with range(), we can create a sequence of integers to map over the keys from a list. Though functional and elegant, this method introduces additional complexity and is slightly less efficient compared to the others.
Python
li = ['apple', 'banana', 'orange']
d = dict(zip(li, map(lambda x: x, range(len(li)))))
print(d)
Output{'apple': 0, 'banana': 1, 'orange': 2}
Explanation: map() applies the identity function lambda x: x to each value in the range(len(li)), effectively creating a sequence of indices. The zip() function pairs each element of li with its corresponding index and dict() converts these pairs into a dictionary, mapping each element to its index.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read