Put list in dictionary python

Appending to list in Python dictionary [duplicate]

Is there a more elegant way to write this code? What I am doing: I have keys and dates. There can be a number of dates assigned to a key and so I am creating a dictionary of lists of dates to represent this. The following code works fine, but I was hoping for a more elegant and Pythonic method.

dates_dict = dict() for key, date in cur: if key in dates_dict: dates_dictPut list in dictionary python.append(date) else: dates_dictPut list in dictionary python = [date] 
dates_dict = dict() for key, date in cur: dates_dictPut list in dictionary python = dates_dict.get(key, []).append(date) 

@Mawg this was a while ago, but I was probably using a cursor object associated with Python’s sqlite3 library.

3 Answers 3

list.append returns None , since it is an in-place operation and you are assigning it back to dates_dictPut list in dictionary python . So, the next time when you do dates_dict.get(key, []).append you are actually doing None.append . That is why it is failing. Instead, you can simply do

dates_dict.setdefault(key, []).append(date) 

But, we have collections.defaultdict for this purpose only. You can do something like this

from collections import defaultdict dates_dict = defaultdict(list) for key, date in cur: dates_dictPut list in dictionary python.append(date) 

This will create a new list object, if the key is not found in the dictionary.

Читайте также:  Язык си шарп операторы

Note: Since the defaultdict will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.

Источник

Python Convert List to Dictionary: A Complete Guide

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

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

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

Python Lists and Dictionaries

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

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

takeout_prices = [2.50, 2.75, 4.50, 5.00]

Our list called takeout_prices contains four values.

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

Dictionaries are useful if you 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 cannot label each value.

Python Convert List to Dictionary

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

Let’s quickly summarize these methods:

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

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

Python Convert List to Dictionary: dict.fromkeys()

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

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

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

You can only specify one value to be assigned to every key. You cannot say that one key should have one value and another key should have a different value.

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

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

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

We first declare a Python variable called fruits which stores the names of the keys we want to use in our dictionary.

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

If we 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

We can also use a technique called dictionary comprehension to convert a Python list to a dictionary using the same values.

A dictionary comprehension is similar to a list comprehension in that both methods create a new value of their respective data types. Dictionary comprehensions use pointed brackets (<>) whereas list comprehensions use square brackets ([]).

Let’s convert our list of fruits to a dictionary using dictionary comprehension:

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

First, 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 dictionary to the console.

Python Convert List to Dictionary: zip()

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

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match 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

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

Suppose we have two lists: one containing a list of fruits, and the other containing the price for an individual piece of fruit. We want to create a single dictionary that stores the name of a fruit, alongside its price. We can use the following code to accomplish this task:

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

First, we have specified two lists: a list of fruits, and a list of prices. Then, we have used the zip() function to merge our two lists together. The zip() function returns a list of merged tuples. Because 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 dictionary using the same values, you can use the dict.fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.

In this tutorial, we used examples to demonstrate how to use three approaches to convert a list to a dictionary in Python. Now you’re ready to start converting Python lists to dictionaries like 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 you can use to build your knowledge of coding in Python.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

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

  • Put list in dictionary python – Key:Value pairs as continuous elements of list.
  • Put list in dictionary python, [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 Put list in dictionary python 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 Put list in dictionary python 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 Put list in dictionary python 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.

Источник

Оцените статью