Python list index to dict

How to Convert a List to Dictionary in Python

To convert a list to a dictionary in Python, you can use “dictionary comprehension”, which creates a key-value pair of consecutive elements and then typecast a list to dictionary type.

Example 1

def listToDict(lst): op = return op lst = ['m', 1, 'b', 2, 'k', 3] print(listToDict(lst)) 

In the above example, we used the for loop to separate odd and even elements and then the range() function to form the odd values to the key and values to the dictionary.

Example 2

To convert a list to a dictionary with the same values, you can use dictionary comprehension. Each key’s value will be the same.

def listToDict(lst): op = return op lst = ['millie', 'caleb', 'finn', 'sadie', 'noah'] print(listToDict(lst))

All the list elements became keys in the above example, and 5 is the value for all the elements.

Convert a list to a dictionary Using a loop

# Let's say we have a list of tuples where # each tuple consists of two elements: key and value list_of_tuples = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # We initialize an empty dictionary dict_from_list = <> # We iterate over each tuple in the list for item in list_of_tuples: # The first element of the tuple is the key and # the second element is the value. key = item[0] value = item[1] # We add the key-value pair to the dictionary. dict_from_listPython list index to dict = value # Now dict_from_list is a dictionary that # corresponds to the given list of tuples. print(dict_from_list)

Convert a list to a dictionary Using Lambda

# Suppose we have the following list of tuples list_of_tuples = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # Use map() to apply a lambda function to the list of tuples dict_from_list = print(dict_from_list) 

Convert a list to a dictionary Using dict.fromKeys()

def listToDict(lst): op = dict.fromkeys(lst , 5) return op lst = ['millie', 'caleb', 'finn', 'sadie', 'noah'] print(listToDict(lst))

The dict.fromKeys() accepts a list and default value. It returns a dictionary with items in the list as keys. All dictionary items will have the same value passed in fromkeys().

Converting list elements as values in the dictionary with indexed keys

def listToDict(lst): op = return op lst = ['millie', 'caleb', 'finn', 'sadie', 'noah'] print(listToDict(lst))

Converting two lists into a dictionary

lstStr = ['millie', 'caleb', 'finn', 'sadie', 'noah'] lstInt = [11, 21, 19, 29, 46]

We will take the first list as the keys for the dictionary and the second list as values.

To achieve that and create a dictionary from two lists, we can use the zip() function.

def listToDict(lstA, lstB): zippedLst = zip(lstA, lstB) op = dict(zippedLst) return op lstStr = ['millie', 'caleb', 'finn', 'sadie', 'noah'] lstInt = [11, 21, 19, 29, 46] print(listToDict(lstStr, lstInt))

Converting the list of tuples to the dictionary

def listToDict(lstTup): op = dict(lstTup) return op lstTuple = [('millie', 11), ('caleb', 21), ('finn', 19), ('sadie', 29), ('noah', 46)] print(listToDict(lstTuple))

Convert a list to a dictionary using list comprehension and slicing

# Suppose we have the following list my_list = ['a', 1, 'b', 2, 'c', 3, 'd', 4] # Convert to dictionary using list comprehension and slicing dict_from_list = print(dict_from_list) 

That’s it for this tutorial.

Источник

Python – Convert List to Dictionary

There are many ways in which you can interpret the data in list as keys and values, and convert this list into a dictionary.

Some of the formats of lists are

  • Python list index to dict – Key:Value pairs as continuous elements of list.
  • Python list index to dict, [value_1, value_2, . ] – Keys are in one list, and Values are in another list.
  • [(key_1, value_1), (key_2, value_2), . ] Key:Value pairs as tuples, and these tuples are elements of the list.

Also, some of the other scenarios are:

  • Converting Python List to dictionary with list element as key and index as value.
  • Converting Python List to dictionary with list element as key and a default for value.

In this tutorial, we will learn how to convert these formats of list to dictionary, with the help of well detailed example programs.

Examples

1. Convert given list to a dictionary

In this example, we will convert the list of format Python list index to dict to dictionary of .

We will use dictionary comprehension to convert this type of list to dictionary.

Python Program

myList = ['a', 'apple', 'b', 'banana', 'c', 'cherry'] myDict = print(myDict) 

2. Convert a list of keys and a list of values into a dictionary

In this example, we will convert a list of format [(key_1, value_1), (key_2, value_2), . ] to dictionary of .

We will use dictionary comprehension to convert this lists of keys and values to dictionary.

Python Program

listKeys = ['a', 'b', 'c'] listValues = ['apple', 'banana', 'cherry'] myDict = print(myDict) 

3. Convert list of tuples into a dictionary

In this example, we will convert a list of format [(key_1, value_1), (key_2, value_2), . ] to dictionary of .

We will use dictionary comprehension to convert list of tuples to dictionary.

Python Program

myList = [('a', 'apple'), ('b', 'banana'), ('c', 'cherry')] myDict = print(myDict) 

4. Convert list into dictionary with index as value

In this example, we will convert a list of format Python list index to dict to dictionary of .

Python Program

myList = ['a', 'b', 'c'] myDict = print(myDict) 

5. Convert list of keys into a dictionary with a default value

In this example, we will convert a list of format Python list index to dict to dictionary of .

Python Program

myList = ['a', 'b', 'c'] defaultValue = 54 myDict = print(myDict) 

Summary

In this tutorial of Python Examples, we learned how to convert a Python List to Dictionary.

Источник

Convert List to Dictionary in Python: Simple Methods to Know

Convert List To Dictionary In Python

Lists and Dictionaries are commonly used data structures in Python designed to store data sequences. Both have their own specific use cases, and it’s important to understand them before converting a list to a dictionary, also throughout this tuitorial, we will see why precisely this conversion is needed, why is it important to have a dictionary, and how to convert a list to a dictionary.

Introduction to Python List

A list in Python is a linear data structure used to store a collection of values that may be of the same or different types. A Python list is enclosed in square brackets[], and each item inside a list is separated by a comma(,).

A Python list is mutable, meaning we can change or modify its contents after its creation inside the Python program.

A Python list stores the elements in an ordered manner and we can access any element in the list directly by its index.

Example:

The below example shows how to create a list in Python and validate it using the type() function.

# Defining a Python list ls = ['AskPython', 'CodeForGeek', 'LinuxforDevices'] # Printing the results print(ls) # Validating the type of 'ls' print(type(ls))

Output:

[‘AskPython’, ‘CodeForGeek’, ‘LinuxforDevices’]

Here we can see that type() returns an object that represents the ‘list’ class, so the ‘ls’ variable is considered a list.

We have a dedicated tutorial on Python List, consider reading it if you want to learn more about the lists.

Introduction to Python Dictionary

A dictionary in Python is a special type of data structure used to store data in a key-value pair format. A single dictionary has two main components: the key and the value, where the key must be a single entity, but the value can be a multi-valued entity such as a list, tuple, etc.

The key and its value are separated by a colon (:) and a comma (,) separates each item (a key-value pair). A dictionary is enclosed in curly brackets <>, and just like lists, dictionaries are also a mutable data structure. A dictionary without any key-value pairs is called an empty dictionary.

A Python dictionary stores the elements in an unordered manner that can access directly by its key.

Example:

The below example shows how to create a dictionary in Python and validate it using the type() function.

# Defining a Python dictionary ds = # Printing the results print(ds) # Validating the type of 'ds' print(type(ds))

Output:

Here we can see that type() returns an object that represents the ‘dict’ class, so the here ‘ds’ variable is considered a dictionary.

Why Convert a List into a Dictionary?

Converting a list into a dictionary can be helpful in many situations where you need to get data in a more precise way. There can be many reasons for this but some that you often see are given below.

  1. Dictionary uses key-value pairs to store data, it is more convenient than a list when data needs to be accessed from a large set of data.
  2. The keys associated with the values are unique so there can be no place of doubt that the data selected is correct.
  3. Data manipulation in the dictionary is easier than a list, that is another reason why a list should convert into a dictionary.
  4. A dictionary is unordered, sometimes we don’t want to maintain order like we have to do in the list.

We have two effective methods to convert a list to a dictionary in Python. Using the zip() function and using dictionary comprehension. Let’s look at each of them so that you can use them as per your requirement.

Convert a Python List to a Dictionary using dictionary comprehension

A list can be converted into a dictionary by using dictionary comprehension which provides an efficient way to create a dictionary by iterating over a list. We can use it with a list to make the corresponding key: value inside the curly brackets <> where each list element becomes a key of the dictionary and the value for each key can be generated accordingly using expressions or functions.

Example:

Let’s see an example that uses dictionary comprehension to convert a list to a Python dictionary.

# Defining a list ls = ['A', 'S', 'K', 'P', 'Y', 'T', 'H', 'O', 'N'] # Using dictionary comprehension to convert the list to a dictionary ds = # Printing the results print("Given list: ", ls) print("Generated dictionary: ", ds) # Validating the type of 'ds' print(type(ds))

In the above code, we have used the Python ord() function to get the ASCII value of each item inside the list and then assigned the ASCII value returned by the ord() function to the corresponding key of the dictionary as its value. This way we end up generating a key-value pair for each item inside the list where each key is a list item itself and the value is its ASCII value, and successfully converted the list into dictionary.

Output:

Given list: [‘A’, ‘S’, ‘K’, ‘P’, ‘Y’, ‘T’, ‘H’, ‘O’, ‘N’] Generated dictionary:

Convert a Python List to a Dictionary using the zip() function

We can convert lists using the zip() function into a single dictionary. The zip() function can take two or more lists as arguments and returns an iterator that contains tuples having the i-th element from each list. Then we can further convert those tuples to a dictionary using the dict() method.

Example:

Let’s now see an example that uses the Python zip() function to convert a list to a Python dictionary.

list1 = ['AskPython', 'CodeForGeek', 'LinuxforDevices'] list2 = ['Python', 'JavaScript', 'Unix/Linux'] ds = dict(zip(list1, list2)) # Printing the results print(ds) # Validating the type of 'ds' print(type(ds))

Here we have used the zip() function and passed two lists as an argument, then we used the dist() method to convert iterator returns by the zip() function into a dictionary having the keys and values. The dictionary keys are the elements of the first list and dictionary values are the elements of the second list.

Output:

Conclusion

Python lists and dictionaries are two crucial data structures in Python used to store data. We can convert the given list into a dictionary if we have to access the element by using its keys not by its order. There are different ways to convert a Python list into a dictionary which we have discussed in this tuitorial. You can choose one according to your need. As a suggestion, using the zip() function is better if you have two or more lists to convert into a single dictionary otherwise using a dictionary comprehension is also a good approach.

Источник

Читайте также:  Java files attribute names
Оцените статью