Python Read Key Value List Into Dictionary

You can convert a Python list to a dictionary using a dictionary comprehension, dict.fromkeys(), or the naught() method. All 3 methods create a new dictionary. They do not modify the existing list.

Python lists and dictionaries are two structures used to store data. Just what if you lot want to convert a list into a dictionary? You lot may want to do this if you want to assign a unique label to each value yous accept stored. This is simply possible in a dictionary.

In that location are a few techniques and built-in functions you tin can use in Python to convert a list to a dictionary. This programming tutorial will discuss, with reference to examples, how to convert a listing into a dictionary in Python.

Python Lists and Dictionaries

Lists and dictionaries are examples of Python collections. They permit you to store multiple similar values together in one information structure.

The list data structure allows you to store data in a specific order. Here is an example of a Python list:

takeout_prices = [two.fifty, 2.75, 4.fifty, five.00]

Our listing called takeout_prices contains four values.

Dictionaries, on the other hand, are unordered, and cannot shop multiple duplicate values.

Here is an example of a Python dictionary:

81% of participants stated they felt more confident about their tech job prospects after attention a bootcamp. Become matched to a bootcamp today.

The boilerplate bootcamp grad spent less than vi months in career transition, from starting a bootcamp to finding their first job.

takeout_prices = { 	'single_chips': 2.50, 	'large_chips': 2.75, 	'single_fish': 4.50, 	'large_fish': 5.00 }

Dictionaries are useful if you lot want to associate labels with each value. Lists are better if you are storing similar data, such as a list of prices or names, where you lot cannot label each value.

Python Convert Listing to Dictionary

You can convert a Python list to a dictionary using the dict.fromkeys() method, a lexicon comprehension, or the zip() method. The zilch() method is useful if you lot want to merge ii lists into a dictionary.

Permit's quickly summarize these methods:

  • dict.fromkeys(): Used to create a dictionary from a list. You can optionally gear up a default value for all keys. You cannot prepare individual values for each item in the dictionary.
  • Lexicon comprehension: Creates a new lexicon from an existing list. You can specify different values for each key in the lexicon. Dictionary comprehensions are similar to Python list comprehensions in construction.
  • zip(): Converts two or more than lists into a list of tuples. You tin use the dict() method to convert the listing of tuples into a dictionary.

Nosotros're going to use each of the three methods above to demonstrate how we can convert a list into a dictionary.

Python Catechumen Listing to Dictionary: dict.fromkeys()

Say that we have a list of fruits that we desire to turn into a dictionary. The value assigned to each fruit should be In stock:

fruits = ["Apple tree", "Pear", "Peach", "Banana"]

We could create this dictionary using the dict.fromkeys() method. This method accepts a listing of keys that you want to turn into a lexicon. Optionally, y'all tin can specify a value you want to assign to every key.

You can just specify one value to exist assigned to every key. You cannot say that one cardinal should have one value and some other key should take a unlike value.

form-submission

Find Your Bootcamp Friction match

  • Career Karma matches you with top tech bootcamps
  • Go exclusive scholarships and prep courses

Let's turn our list of fruits into a dictionary:

fruits = ["Apple", "Pear", "Peach", "Assistant"]  fruit_dictionary = dict.fromkeys(fruits, "In stock")  impress(fruit_dictionary)

Our code returns the objects from this list in a dictionary object:

{'Apple': 'In stock', 'Pear': 'In stock', 'Peach': 'In stock', 'Assistant': 'In stock'}

We starting time declare a Python variable called fruits which stores the names of the keys nosotros want to apply in our dictionary.

We use dict.fromkeys() to create a dictionary that uses the cardinal names we stored in the fruits assortment. This method assigns the value of each key to be In stock. Finally, we print the new lexicon to the panel.

If nosotros did not specify the value In stock in our code, the default value for the keys in our dictionary would be None.

Convert List to Dictionary Python: Dictionary Comprehension

Nosotros can as well use a technique called lexicon comprehension to convert a Python list to a lexicon using the same values.

A dictionary comprehension is like to a list comprehension in that both methods create a new value of their corresponding data types. Lexicon comprehensions employ pointed brackets ({}) whereas list comprehensions use square brackets ([]).

Let'south convert our list of fruits to a dictionary using lexicon comprehension:

fruits = ["Apple", "Pear", "Peach", "Banana"]  fruit_dictionary = { fruit : "In stock" for fruit in fruits }  print(fruit_dictionary)

Our code returns:

{'Apple': 'In stock', 'Pear': 'In stock', 'Peach': 'In stock', 'Banana': 'In stock'}

Kickoff, we declared a list called fruits which stored the names we wanted to move into a dictionary.

Then, we used dictionary comprehension to run through each item in the fruits list. We add an item to our new dictionary for each fruit in our list. The value we assigned to each fruit was In stock. Finally, we printed out our new lexicon to the console.

Venus profile photo

"Career Karma entered my life when I needed it most and quickly helped me lucifer with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

Python Convert List to Dictionary: zip()

In our last instance, we have converted a unmarried list into a lexicon and assigned a default value for each item in the lexicon. Yet, it is possible to convert two lists into a dictionary.

To do so, we can use the Python zip() function. This function lets us merge two lists together. We tin utilise one listing as the keys for the dictionary and the other equally the values.

Suppose we take ii lists: one containing a list of fruits, and the other containing the price for an individual piece of fruit. Nosotros want to create a unmarried lexicon that stores the name of a fruit, alongside its price. We can utilize the following lawmaking to reach this task:

fruits = ["Apple tree", "Pear", "Peach", "Banana"] prices = [0.35, 0.40, 0.40, 0.28]  fruit_dictionary = dict(zip(fruits, prices))  impress(fruit_dictionary)

Our code returns:

{'Apple': 0.35, 'Pear': 0.4, 'Peach': 0.4, 'Banana': 0.28}

Start, we take specified two lists: a list of fruits, and a listing of prices. Then, we have used the zip() role to merge our ii lists together. The zip() part returns a listing of merged tuples. Considering we want a dictionary, we have used dict() to convert our tuples into a dictionary.

Next, we printed the contents of our new dictionary to the console.

Conclusion

To convert a list to a lexicon using the same values, y'all can use the dict.fromkeys() method. To catechumen 2 lists into one dictionary, you tin can apply the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a listing.

In this tutorial, we used examples to demonstrate how to employ three approaches to convert a listing to a dictionary in Python. Now you lot're set up to beginning converting Python lists to dictionaries similar a professional programmer!

Are you interested in learning more about Python? Read our How to Learn Python guide. This guide contains a list of online courses, books, and learning resources yous can use to build your cognition of coding in Python.

pughtherned.blogspot.com

Source: https://careerkarma.com/blog/python-convert-list-to-dictionary/

0 Response to "Python Read Key Value List Into Dictionary"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel