Python list dict objects

8 ways to create Python dictionary of lists

In this Python tutorial, we will understand how to create a Python Dictionary of lists. However, a dictionary of lists basically means creating and assigning values as a list in a Python Dictionary.

In Python, we can create a dictionary of lists using the following 9 methods. Moreover, for each method, we will also illustrate an example.

  1. Using dictionary literals
  2. Using dict() & zip() methods
  3. Using a dictionary comprehension
  4. Using defaultdict() method
  5. Using for loop and append() method
  6. Using setdefault() method
  7. Using dict.fromkeys() method
  8. Using zip_longest() method

Python dictionary of lists

In Python, the dictionary of lists means having a dictionary consisting of values as a list.

Basically, a Python dictionary is an unordered and immutable data type and can be used as a key element. First, we insert key-value within the curly brackets to create a dictionary of lists.

However, to obtain the values of a dictionary, we use the key name within the square brackets.

Let us discuss each method to create a Python dictionary of lists.

Method 1: Using dictionary literals

One of the primary ways to create a Python dictionary of lists is by using the dictionary literals.

Читайте также:  Colt python girls frontline

In Python, we can define dictionary literals by using curly brackets. Within the curly brackets, we use a colon to separate key-value pairs separated by coma.

Here is an example of defining a dictionary of lists using dictionary literals.

# Defining a dictionary of list using dict literals student_marks = < 'James': [72, 63, 87], 'Adam': [56, 65, 69], 'John': [88, 79, 84] ># Calculating the average of each student for x in student_marks.items(): name, marks = x avg = sum(marks)/len(marks) print('Average marks of', name, 'is', avg) 

In the above example, we used the dictionary literals to define a dictionary of lists named students_marks.

After this, we use the for loop to iterate over each key and its list of values and calculate the average marks for each student.

Average marks of James is 74.0 Average marks of Adam is 63.333333333333336 Average marks of John is 83.66666666666667

Method 2: Using dict() and zip()

The dict() constructor is another way to define a dictionary in Python. On the other side, zip() is another built-in Python function that allows aggregate elements from multiple lists to a tuple.

So, in this method, we will use the zip() function to aggregate multiple list data into a tuple. And then, we will use the dict() constructor to convert that tuple to the dictionary.

# Defining keys keys = ['James', 'Adam', 'John'] values = [ [72, 63, 87], [56, 65, 69], [88, 79, 84] ] # Creating dictionary of lists student_marks = dict(zip(keys, values)) # Printing the dictionary print(student_marks)

In the above example, we have taken 2 lists- keys and values. And then we used the dict() and zip() functions to create a dictionary of lists in Python.

Here is the result of the above Python program.

Method 3: Using a dictionary comprehension

In Python, dictionary comprehension is the simplest way to transform existing data into a new dictionary.

So, in this method, we will use the dictionary comprehension method to iterate over elements of lists. And then we combine the data to form another dictionary of lists in Python.

An example related to this approach is given below.

# Defining keys & values keys = ['James', 'Adam', 'John'] values = [ [72, 63, 87], [56, 65, 69], [88, 79, 84] ] # Creating dictionary of lists student_marks = # Printing the dictionary print(student_marks)

In the above example, we have taken 2 lists- keys and values. And then we used the dictionary comprehension method to create a dictionary of lists in Python.

Method 4: Using defaultdict() method

The defaultdict() is part of the collection module. The defaultdict() is a subclass of dict class in Python and the main role of using it is to handle missing keys.

However, we can use the defaultdict() to define a defaultdict with a default value as a list. And after this, we can use the append() method to append values to the lists. This will result in forming a dictionary of lists.

But we jump to the example, we need to understand the syntax of using the defaultdict() in Python.

defaultdict(default_factory)

In the syntax of creating a defaultdict, default_factory is a callable object that returns the default value for a missing key. This callable takes no arguments.

Next, let us look at an example of creating a dictionary of lists using defaultdict() in Python.

# Importing defaultdict from collections import defaultdict # Defining list type as default usa_info = defaultdict(list) # Defining dictionary of lists usa_info['Cities'].append('Austin') usa_info['Cities'].append('Seattle') usa_info['States'].append('California') usa_info['States'].append('Texas') # Printing the dictionary print(usa_info)

In this example, we created a dictionary of lists named usa_info with Cities and States as keys and [Austin, Seattle] and [California, Texas] as values respectively.

Here is another example of using the defaultdict() with for loop and append() method to create a dictionary of lists in Python.

from collections import defaultdict my_new_list = [('Micheal', 18), ('George', 91), ('Oliva', 74)] new_dictionary = defaultdict(list) for new_k, new_val in my_new_list: new_dictionary[new_k].append(new_val) print("Dictionary of lists",new_dictionary)

After writing the above code, Once you will print “new_dictionary” then the result will be displayed as a “. Here the default dict() method is used to iterate over a list of tuples.

Dictionary of lists defaultdict(, )

Method 5: Using for loop and append()

  • In this technique, we will first define an empty dictionary
  • Then we will define a key with its value type as a list
  • Next, we will define a list of values
  • Then we will use the for loop to iterate over each value given in the list and use the append() method to add the list value
# Creating an empty dictionary student_marks = <> # Adding list as value student_marks["James"] = list() # Creating a list marks = [ 50, 54, 76] # Using for loop to iterate over each list value for val in marks: # Adding list as values in the student_marks student_marks["James"].append(val) print(student_marks)

Once we execute the above Python program, we will get the following dictionary of lists in Python.

Method 6: Using setdefault()

Just like defaultdict(), we can also use the setdefault() built-in function to handle missing keys.

The setdefault() method takes a key and a default value as arguments and returns the value of the key in the dictionary. If the key does not exist in the dictionary, the key is added with the default value.

Here is an example of using the setdefault() in Python to create a dictionary of lists.

# Creating an empty dictionary student_marks = <> # Defining list of values james_marks = [76, 67, 81] # Appending all values to the key for marks in james_marks: student_marks.setdefault('James', []).append(marks) # Printing the resukt print(student_marks)

After executing the above Python program, we will get the following result.

Method 7: Using dict.fromkeys

The dict.fromkeys() is a built-in dictionary method in Python that allows to the creation of a new Python dictionary with specified keys and default values.

And we can use the same method to create a dictionary where all values are set to the same list object.

Here is an example of this implementation in Python.

# Defining keys and values keys = ['James', 'Adam', 'John'] values = [88, 79, 84] # Creating dictionary of lists student_marks = dict.fromkeys(keys, []) for key in keys: student_marksPython list dict objects = values # Printing the dictionary print(student_marks)

In the example, we defined 2 lists- keys and values. After this, we used the dict.fromkeys() method to create a dictionary of lists with empty list values.

In the last, we utilized the for loop to set the same list values for each key given in the students_marks dictionary.

Method 8: Using zip_longest

The zip_longest is a built-in function that comes under the itertools module. This allows us to aggregate elements from multiple iterables of potentially different lengths, filling in with a specified value for shorter iterables.

In this method, we will use the zip_longest() function to aggregate keys and a list of values. And result in forming a tuple. After this, we will use the dict() constructor to convert that tuple into a dictionary.

This will result in forming a dictionary of lists in Python.

# importing zip_longest from itertools import zip_longest # Defining keys & values keys = ['James', 'Adam', 'John'] values = [ [72, 63, 87], [56, 65, 69], [88, 79, 84] ] # Creating dictionary of lists student_marks = dict(zip_longest(keys, values, fillvalue=[])) # Printing the dictionary print(student_marks)

In this example, we use the zip_longest() function to create a dictionary of lists named student_marks.

Once we execute the above Python program, we will get the following result.

Python dictionary of lists

You may also like to read the following Python tutorials.

Conclusion

So, in this Python tutorial, we understood how to create a Python Dictionary of lists using 8 different methods. However, we have also illustrated multiple examples of each method in Python.

Here is the set of methods we discussed.

  • Python Dictionary of lists using dictionary literals
  • Python Dictionary of lists using dict() & zip() methods
  • Python Dictionary of lists using a dictionary comprehension
  • Python Dictionary of lists using defaultdict() method
  • Python Dictionary of lists using for loop and append() method
  • Python Dictionary of lists using setdefault() method
  • Python Dictionary of lists using dict.fromkeys() method
  • Python Dictionary of lists using zip_longest() method

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Python List of Dictionaries

In Python, you can have a List of Dictionaries. You already know that elements of the Python List could be objects of any type.

In this tutorial, we will learn how to create a list of dictionaries, how to access them, how to append a dictionary to list and how to modify them.

Create a List of Dictionaries in Python

In the following program, we create a list of length 3, where all the three elements are of type dict.

Python Program

Each element of the list is a dictionary.

Access key:value pairs in List of Dictionaries

Dictionary is like any element in a list. Therefore, you can access each dictionary of the list using index.

And we know how to access a specific key:value of the dictionary using key.

In the following program, we shall print some of the values of dictionaries in list using keys.

Python Program

myList = [ < 'foo':12, 'bar':14 >, < 'moo':52, 'car':641 >, < 'doo':6, 'tar':84 >] print(myList[0]) print(myList[0]['bar']) print(myList[1]) print(myList[1]['moo']) print(myList[2]) print(myList[2]['doo'])

Update key:value pairs of a Dictionary in List of Dictionaries

In the following program, we shall update some of the key:value pairs of dictionaries in list: Update value for a key in the first dictionary, add a key:value pair to the second dictionary, delete a key:value pair from the third dictionary.

Python Program

myList = [ < 'foo':12, 'bar':14 >, < 'moo':52, 'car':641 >, < 'doo':6, 'tar':84 >] #update value for 'bar' in first dictionary myList[0]['bar'] = 52 #add a new key:value pair to second dictionary myList[1]['gar'] = 38 #delete a key:value pair from third dictionary del myList[2]['doo'] print(myList)

Append a Dictionary to List of Dictionaries

In the following program, we shall append a dictionary to the list of dictionaries.

Python Program

myList = [ < 'foo':12, 'bar':14 >, < 'moo':52, 'car':641 >, < 'doo':6, 'tar':84 >] #append dictionary to list myList.append() print(myList)

Summary

In this tutorial of Python Examples, we learned about list of dictionaries in Python and different operations on the elements of it, with the help of well detailed examples.

Источник

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