Python dictionary of lists – Detailed Guide

In this Python tutorial, we will discuss the Python dictionary of lists. Here we will also cover the below examples:

  • Python dictionary of lists append
  • Python dictionary of lists get value
  • Python dictionary of lists to dataframe
  • Python dictionary of lists to CSV
  • Python dictionary of lists iterate
  • Python dictionary of lists to list of dictionaries
  • Python dictionary of lists to Json
  • Python dictionary of lists access
  • Python dictionary of lists example
  • Python dictionary of lists sort
  • Python dictionary list all keys
  • Python dictionary list of Keys and values
  • Python dictionary list of tuple
  • Python dictionary with list comprehension
  • Python dict with list append
  • Python dict with list items
  • Python dict in list remove duplicate
  • Python dictionary of two lists
  • Python dictionary list update
  • Python dictionary list index
  • Python dictionary of lists get all values
  • Python dictionary list value append
  • Python dictionary vs list
  • Python filter dictionary list by value
  • Python dictionary of numpy array

Python dictionary of lists

  • In this program, we will discuss how to create a dictionary of lists.
  • In Python, the dictionary of lists means we have to assign values as a list.
  • In Python dictionary, it is an unordered and immutable data type and can be used as a keys element. To create a dictionary of lists, first, we insert key-value within the curly brackets and to obtain the values of a dictionary, and then use the key name within the square brackets.

Examples:

Let’s take an example and check how to create a dictionary of lists in Python

By using the default dict() method we can solve this task

Syntax:

Here is the Syntax of the default dict() method

defaultdict(default_factory)

Source Code:

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 “{‘Micheal’:[18]}. Here the default dict() method is used to iterate over a list of tuples.

Python dictionary of lists
Python dictionary of lists

An alternative way to check how to create a dictionary of lists is by using a subscript method

In this example, we have inserted a list as a value in the dictionary by applying the method subscript. In a Python dictionary, the subscript method can be added to an existing value and can be modified to a Python dictionary.

Source Code:

new_emp_dictionary = {}

new_emp_dictionary["new_ke"] = [64, 91]
new_emp_dictionary["new_ke2"] = ["Germany", "Australia", "China"]

print("Created dictionary of lists:",new_emp_dictionary)

Here is the Output of the following given code

Python dictionary of lists
Python dictionary of lists

Read: Python dictionary extend

Python dictionary of lists append

  • Here we can see how to append lists in the dictionary.
  • In this program, we have created a list and append the new list to the value. In Python dictionary, the append() method is used to insert the element in the given dictionary.

Source Code:

new_empty_dict = {}

new_empty_dict["Student_id"] = [26, 34]
nw_list = ['Oliva', 'Elijah', 'George']
new_empty_dict["Student_id"].append(nw_list)
print(new_empty_dict)

In the above code first, we initialize an empty dictionary called “new_empty_dictionary” and then add lists as values by creating dict[key]. After that create a new list which we have to append this list as a sublist in “new_empty_dict”. Once you will print ‘new_empty_dict’ then the output will display as ‘{“student_id”:[26,34]}.

You can refer to the below Screenshot

Python dictionary of lists append
Python dictionary of lists append

Another example to append lists in the dictionary

Source Code:

country_name = {'France':[65, 28, 89], 'Germany':[16, 32, 81]}

country_name['Germany'].append(665)
print(country_name)

In the above code first, we initialize a dictionary that stores elements in the form of key-value pairs. After that assign key elements as a list and append it with the value ‘665’.

Here is the implementation of the following given code

Python dictionary of lists append
Python dictionary of lists append

Read: Python string to list

Python dictionary of lists get value

  • Let us see how to get values in a Python dictionary of lists.
  • To perform this task we use its key as a list that gives us the values of that element, which is a list.

Example:

student_info = {'Student_id':[85, 47, 49], 'Student_age':[91, 116, 913]}

print("values from list1:",student_info['Student_id'])
print("values from second list:",student_info['Student_age'])

In the above program, we have created a dictionary and call print statement to display the result in the form of a list that contains only values.

You can refer to the below Screenshot

Python dictionary of lists get value
Python dictionary of lists get value

Another example to check how to get values from Python dictionary of lists

By using the dict.values() method we can perform this particular task and this function return an object that appears as a list of all the values from a given dictionary.

Source Code:

d = {"key1": [9,2,3], "key2": [17,81,76]}

b = list(d.values())
print(b)

In this example, we use the list() function in which we have passed the dict. values() method as an argument. Once you will print “b” then the output will display as [9,2,3].

Here is the execution of the following given code

Python dictionary of lists get value
Python dictionary of lists get value

Read: Python Dictionary Copy with Examples

Python dictionary of lists to dataframe

  • In this program, we will see how to create a dictionary of lists to the dataframe.
  • In this example, we have converted a dictionary of lists to a dataframe by using the dataframe() method where the keys in the dictionary are considered as a column header and the values are represented as column values.
  • In Python, the dataframe is a data structure in the form of rows and columns and it is available in the Python pandas module.

Example:

import pandas as pd

student_info = {'student_name':['Oliva','Potter'],'Student_age':[32,21]}
df2 = pd.DataFrame(student_info)
print(df2)

In the above example as you can see, first we imported a pandas library and then create a dictionary in which each key corresponds to a column heading in the dataframe.

Here is the Output of the following given code

Python dictionary of lists to dataframe
Python dictionary of lists to dataframe

Read: Python dictionary multiple keys

Python dictionary of lists to CSV

  • Let us see how to create a dictionary of lists and convert them into CSV files.
  • By using the CSV.dictwriter() method we can write a list of dictionaries to a CSV file. In Python, this method returns a writer object which converts the data into strings.
  • In Python, if you want to open a filename with write access then you can use the “w” keyword as an argument in the open() method.

Source Code:

import csv
new_dictionary = {"China": [23,45,67], "Egypt": [71,189,672], "Australia": [823,567.910]}
with open("test1.csv", "w") as f:
   new_val = csv.writer(f)
   new_val.writerow(new_dictionary.keys())
   new_val.writerows(zip(*new_dictionary.values()))

In the above code, we apply the concept of the writer. writerow() for multiple row values and this method takes only the key values and within this function, we have passed zip function as an argument.

Here is the Screenshot and Output code of the CSV file

Python dictionary of lists to CSV
Python dictionary of lists to CSV

Source Code:

import csv
new_dictionary = {"China": [23,45,67], "Egypt": [71,189,672], "Australia": [823,567.910]}
with open("test1.csv", "w") as f:
   new_val = csv.writer(f)
   new_val.writerow(new_dictionary.keys())
   new_val.writerows(zip(*new_dictionary.values()))

Note: This is an input code for creating a dictionary of lists and the result will display in the CSV file mode

You can refer to the below Screenshot for creating a dictionary of lists to CSV

Python dictionary of lists to CSV
Python dictionary of lists to CSV

Read: Remove character from string Python

Python dictionary of lists iterate

  • Here we can see how to iterate value lists in a Python dictionary.
  • By using the list comprehension method we will iterate all the items of the dictionary. In this example, we have created a dictionary with the list as values for most of the keys that means multiple values are corresponding with some keys.

Source Code:

employee_dict = {'Potter' : [72,187,924], 'Chris' : [179,823,349], 'Hemsworth' : [147,723,912]}

new_output = [[z for z in employee_dict[u]] for u in employee_dict.keys()]

print(new_output)

In the above example, Once you will print “new_output” then the result will be displayed as a [72,187,924]. After that, we iterate over all key-value pairs by using the list comprehension method and each pair will produce a list of pairs where each key element will remain the same but values will be changed in each pair.

Here is the execution of the following given code

Python dictionary of lists iterate
Python dictionary of lists iterate

Read: Python find max value in a dictionary

Python dictionary of lists to list of dictionaries

  • In this program, we will see how to convert a dictionary of lists to list of dictionaries.
  • By using the list comprehension method, we can easily iterate through each dictionary element in the form of a key-value pair and associates it with a list of dictionaries.

Source Code:

country_name = { "China" : [843,956], "Turkey" : [554,125], "Spain" : [819,167] }


new_output = [{new_k : new_val[r] for new_k, new_val in country_name.items()}
		for r in range(2)]

print (new_output)

Here is the implementation of the following given code

Python dictionary of lists to list of dictionaries
Python dictionary of lists to list of dictionaries

Read: How to create an empty Python dictionary

Python dictionary of lists to JSON

  • Let us see how to convert the dictionary of lists to JSON.
  • By using the list comprehension method, we can perform this task first we have imported a JSON library and then create a dictionary. Another variable detail is declared to contain the dictionary into JSON by using JSON.dumps() method.

Example:

import json

new_dictionary = {

     'Colors_name' : ['Orange', 'Blue', 'Yellow'],
     'Fruits_name'  : ['Banana', 'Cherry', 'Apple']

}
z = [{"Colors_name":m, "Fruits_name":n} for m, n in zip(new_dictionary["Colors_name"], new_dictionary["Fruits_name"])]
dict_json = json.dumps(z)
print(dict_json)

You can refer to the below Screenshot

Python dictionary of lists to json
Python dictionary of lists to JSON

Read: Python Dictionary to CSV

Python dictionary of lists access

  • In this program, we will see how to access a dictionary of lists.
  • Here we can apply list comprehension method to access a dictionary of lists.

Example:

new_dictionary = dict()

new_values = ['829', '452', '158']

for i in new_values:
	for new_element in range(int(i), int(i) + 2):
		new_dictionary.setdefault(new_element, []).append(i)

print(new_dictionary)

Here is the Screenshot of the following given code

Python dictionary of lists access
Python dictionary of lists access

Python dictionary of lists example

Let’s take an example with different methods and check how to create a dictionary of lists.

Source Code:

dict_val = [89,183]
my_new_val2 = [293,817]
emp_dic = {}
for i in dict_val:
	emp_dic[i]=[i, ]
for j in my_new_val2:
  emp_dic[j]=[j, ]

print(emp_dic)

In the above code first, we initialize a list ‘dict_val’, and then we have to create an empty list. Now we use for loop method to iterate each value that is available in the list.

Output:

Python dictionary of lists example
Python dictionary of lists example

Read: Python convert dictionary to an array

Python dictionary of lists sort

  • Let us see how to sort a dictionary of lists in Python.
  • In Python to sort a dictionary by value or key, we can use the sorted() function with this function we can sort dictionaries by key and it takes three parameters iterable, key, and reverse.
  • Suppose we have a dictionary in Python that contains the elements of our country name. So now we want to sort the dictionary of lists in ascending order of values and keys.

Example:

Country_dictionary = {'Paris': [67,187,9,41],
			'England': [118,724,90,54],
			'Japan': [165,43,256,87]}

new_output = {new_k : sorted(Country_dictionary[new_k]) for new_k in sorted(Country_dictionary)}
print("Sorted dictionary list:",new_output)

In the above code, we use the concept of the sorted()+ loop method. While using for loop the [new_k] is to sort the result iterable by inner key values.

You can refer to the below Screenshot

Python dictionary of lists sort
Python dictionary of lists sort

Read: Python dictionary of tuples

Python dictionary list all keys

  • In this program, we will discuss how to get all keys from the dictionary list.
  • In Python, the dictionary provides function keys() which helps the user to get all keys from the dictionary list and this method will always return an iterable sequence that displays a list that contains all the keys from a given dictionary list.

Example:

employee_dictionary = {'Adam':[93,21,117], 'Gilchrist': [48,95,643], 'Hayden': [70,61,58]}

print("All keys from dictionary:",employee_dictionary.keys())

In the above code first, we initialize a dictionary that contains elements in the form of key-value pairs. Now Once you will print “employee_dictionary.keys()” then the output will display as [‘adam’, ‘Gilchrist’,’Hayden’].

Here is the implementation of the following given code

Python dictionary list all keys
Python dictionary list all keys

Alternative way to check how to get all keys from dictionary list

By using the list comprehension method we can iterate over all keys of a given dictionary and then use the print statement it will display each key one by one.

Source Code

employee_dictionary = {'Adam':[93,21,117], 'Gilchrist': [48,95,643], 'Hayden': [70,61,58]}

[print("Get all keys from dictionary:",new_k) for new_k in employee_dictionary]

Here is the Screenshot of the following given code

Python dictionary list all keys
Python dictionary list all keys

Read: Python creates a dictionary from two lists

Python dictionary list of keys and value

  • Here we can see how to create a dictionary by a list of keys and values.
  • The easiest way to create a dictionary from a list of keys and values is to apply the dict() function and inside the function take the zip() method as an argument.

Source Code:

new_dict_keys = ['Cherry','Orange','Mangoes','Banana']

new_dict_values = [56,98,67,119]
int_dict = dict(zip(new_dict_values,new_dict_keys))
print("Create dictionary:",int_dict)

Here is the execution of the following given code

Python dictionary list of keys and value
Python dictionary list of keys and value

Another example to create dictionary by a list of keys and values

By using the dictionary comprehension method, we can merge two sets of data which are in the form of lists.

Source Code:

Country_name = ['Japan', 'U.S.A', 'China','Istanbul']
new_val = [96,118,438,702]
 
new_output = {Country_name[m]: new_val[m] for m in range(len(Country_name))}
print(new_output)   

This program is another approach to create a dictionary list by values and keys. To do this first we initialize a lists ‘Country_name’ that contains elements in the form of keys. Now create a variable and assign both the list as a dictionary comprehension method. Once you will print ‘new_output’ then it will display as {‘japan:96’}.

You can refer below to the Screenshot

Python dictionary list of keys and value
Python dictionary list of keys and value

Read: Python dictionary pop

Python dictionary list of tuple

  • Here we can discuss how to convert a dictionary list of tuples.
  • In Python, the dictionary provides a function that is dict.items() method and this method will always return a view object that appears as a list of dictionaries that contains key-value tuple pair.

Example:

student_name = {"Elijah": 192, "Oliva": 278, "Potter": 589}

new_lis_tup = student_name.items()
new_result = list(new_lis_tup)
print(new_result)

In the above example, we have converted a dictionary into a list of tuples by using dict.items() method with dictionary “student_name” and this method will always return a list of key-value pairs as an object. Now use the list() method and pass ‘new_lis_tup’ as an argument and call print statement it will display the result which is in the form of a list tuple.

Here is the implementation of the following given code

Python dictionary list of tuple
Python dictionary list of tuple

An alternative way to check how to convert a dictionary list of tuple

By using the combination of for loop and append() method we can perform this particular task.

Source code:

employee_name = {"Chris": 729, "George": 190, "Oliva": 389}

new_element = [] 

for new_k in employee_name: 
   new_element.append((new_k, employee_name[new_k])) 
print("Convert dictionary to list of tuple:",new_element)

In the above example first, we have created an empty list and then iterate all key elements of the dictionary by using a for loop method. In Python, this method works to insert each element one by one into the list.

Here is the Output of the following given code

Python dictionary list of tuple
Python dictionary list of tuple

Read: Python loop through a list

Python dictionary with list comprehension

  • In Python to create a dictionary with list comprehension, we use the concept of zip() function, and this method provides a list of tuples.
  • In this example, we created two lists that are keys and values and then use the list comprehension method that helps to generate a dictionary object.

Source Code:

Country_key = ['Australia','France','Polland','Japan']
Country_new_val = [56,83,19,89]

new_dictionary = { new_key:new_val for (new_key,new_val) in zip(Country_key, Country_new_val)}
print (new_dictionary)

You can refer to the below Screenshot

Python dictionary with list comprehension
Python dictionary with list comprehension

Python dict with list items

  • Here we can see how to create a dictionary with list items.
  • By using list() and dict[key] method we can assign lists to the values of dictionary.

Source Code:

init_dict = {}
init_dict["Newzealand"] = [67,29,87]
init_dict["Switzerland"] = [118,490,289]
init_dict["Polland"] = [102,201,801]

print("Created dictionary with list items:",init_dict)

In the above code first, we have to initialize an empty dictionary and then use dict[key]=value syntax this method will help the user to add a list in an empty dictionary. Now Once you will print “init_dict” then it will display the result which is in the form of a dictionary.

Here is the Output of the following given code

Python dict with list items
Python dict with list items

Python dict in list remove duplicate

  • In this program, we will discuss how to remove duplicate dictionaries in lists.
  • With the use of the list comprehension method, we can solve this task. In this example, we have created a list that contains multiple dictionaries with duplicate elements.
  • Now we have to remove duplicate dictionary from the list to do this first, we create a variable ‘new_output’ and assign a list comprehension method in which the enumerator function allows you to loop over iterable objects and convert them into a list.

Source Code:

my_new_list = [{"Rose" : 1}, {"Lilly" : 2}, {"Tulip" : 3}, {"Lotus" : 2},{"Rose":1}]

new_output = [m for u, m in enumerate(my_new_list) if m not in my_new_list[u + 2:]]

print ("Remove duplicate from list:",new_output)

Here is the execution of the following given code

Python dict in list remove duplicate
Python dict in list remove duplicate

Read: Python dictionary contains

Python dictionary of two lists

  • Let us see how to create a dictionary from two lists in Python.
  • In this example, we can combine two lists and get a new dictionary. To do this task we use the zip(iterator) method and within this function, we have passed two given lists ” new_list”, “new_val”. Now to convert the zip(iterator) to a dictionary we use the dict() method.

Example:

new_list = ["t", "u"]

new_val = [18,56]
m = zip(new_list, new_val)
init_dict = dict(m)
print(init_dict)

Here is the Screenshot of the following given code

Python dictionary of two lists
Python dictionary of two lists

Another example to create a dictionary from two list

By using the dictionary comprehension method

Source Code:

employee_name = ['Arish', 'Elijah', 'Oliva','Hemsworth']
val_lis = [193,692,108,297]
 
new_result = {employee_name[n]: val_lis[n] for n in range(len(employee_name))}
print("Created dictionary from two lists:",new_result)

This program is another approach to create a dictionary from two lists. To do this first we initialize a lists ’employee_name’ that contains elements in the form of keys. Now create a variable and assign both the list as a dictionary comprehension method. Once you will print ‘new_output’ then it will display as {}.

You can refer below to the Screenshot

Python dictionary of two lists
Python dictionary of two lists

Read: Python for loop index

Python dictionary list update

  • Let us discuss how to update the values of a list of dictionaries in Python.
  • In this program, we have created a list of dictionaries and then we have to access the dictionary by the index [0]. Now we can use the append() function to insert the ‘George’ value in the given list.
  • If you want to access ‘stu_name’ attribute of the first dictionary then you can use ‘new_student_list'[0][‘stu_name’]. Now if you want to update the value of that list you can use the append() function and also you can apply the pop() method to remove an element from the list.

Source Code:

new_student_list = [
  {'Desgination' : 'Developer', 'stu_name' : ['Chris', 'James']},
  {'Desgination2' : 'Tester', 'stu_name' : ['Hemsworth', 'Potter']}
]
new_student_list[0]
new_student_list[0]['stu_name'].append('George')
new_student_list[0]['stu_name'].pop(2)
print(new_student_list)

Here is the implementation of the following given code

Python dictionary list update
Python dictionary list update

Python dictionary list index

  • Here we can see how to create a dictionary with a list-index value.
  • To perform this task we can use the concept of dict() and enumerator() method. In Python the enumerate() method allows the user to iterate a given sequence and it takes an iterable as an argument.

Source Code:

fruits_name = ['Oranges', 'Grapes', 'Banana'] #list_name

new_output = dict(enumerate(fruits_name))
print(new_output)

In the above code, first, we initialize a list ‘fruits_name’ which contains elements that are in the form of a string. Now declare a variable and use the enumerator function to get the indexes along with that we have to use the dict() method to convert the list to a dictionary.

You can refer to the below Screenshot

Python dictionary list index
Python dictionary list index

Read: Python dictionary comprehension

Python dictionary of list get all values

  • In this program, we will discuss how to get all values from the dictionary list.
  • In Python, the dictionary provides a function value() which helps the user to get all values from the dictionary list and this method will always return an iterable sequence that displays a list that contains all the values from the given dictionary list.

Example:

student_information = {'Oliva':[170,439,198], 'Cinderalla': [810,289,534], 'Mathew': [129,309,775]}

print("All values from dictionary:",student_information.values())

Explanation:

In the above code first, we initialize a dictionary that contains elements in the form of key-value pairs. Now Once you will print “student_information.values()” then the output will display as ([[170,439,198]]).

Here is the Screenshot of the following given code

Python dictionary of list get all values
Python dictionary of the list get all values

Read: Python dictionary find a key by value

Python dictionary list value append

  • Here we can see how to create a dictionary by appending a list value.
  • By using default.dict() method we will initailize a dictionary and the default value is based on type argument.

Source Code:

import collections

my_new_dictionary = collections.defaultdict(list)
my_new_dictionary["127"].append("Potter")
print(my_new_dictionary)

Here is the Output of the following given code

Python dictionary list value append
Python dictionary list value append

Python dictionary vs list

  • Python dictionary is a mutable collection of data which is in the form of unique keys and values and it is denoted by curly{} brackets and separated by ‘comma’. While the values can be of any datatype and keys elements must be immutable.
  • In Python, a list is declared by storing all the elements within square brackets [] and separated by ‘comma’. While the items may be integer, float, and string, etc.
  • In the case of the Python list, the order of the values entered is maintained and in the case of the Python dictionary, there is no guarantee for maintaining order.
  • There are very easy and useful methods in the list and Python lists do the work in the collection data structure while dictionary allows the user to iterate over its key and value by using for loop method.

Example:

Let’s take an example and see the difference between a list and a dictionary

Source Code:

new_dictionary = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

print("New dict contains keys and values:",new_dictionary)
new_list = [3,4,5,9,12] 
print("Generated list contains intger values:",new_list) 

Here we just simply created a dictionary and list which contains elements. Now once you will print “new_dictionary” and “new_list” then the output will display “[3,4,5,9,12]”.

You can refer below to the Screenshot

Python dictionary vs list
Python dictionary vs list

Python filter dictionary list by value

  • Here we can see how to filter a dictionary list by value.
  • In Python the filter() function will filter all the elements and display certain keys from the dictionary based on the given criteria.

Source Code:

new_lis_val = [{'a':'z'},{'a':'z'},{'a':'z'}, {'a':'u'}]

selected_list = ['u']
filt_dict = [m for m in new_lis_val if m['a'] in selected_list]
print(filt_dict)

In the above example, we have created a list of dictionaries and each dictionary has a key ‘a’ which can have values of ‘z’ and ‘u’. Now we created a list of key values ‘selected_list’. Now we want to filter out these dictionaries into a list.

Here is the Output of the following given code

Python filter dictionary list by value
Python filter dictionary list by value

Read: Python dictionary increment value

Python dictionary of numpy array

  • In this program, we will discuss how to convert a dictionary to a numpy array.
  • To perform this particular task we can apply the method dict.items(). In Python the dict.items() method returns a collection of key-value pair elements and then use list(obj) we can convert a dictionary to a list.

Example:

import numpy as np

nump_dict = {6: 36, 4: 16, 8: 64, 9: 81,
				11: 121, 12: 144, 13: 169}


new_outpt = np.array(list(nump_dict.items()))
print("Converted dictionary to numpy array:",new_outpt)

In this example first, we have created a dictionary that contains a key as a number and value as its square. Now we have converted a dictionary to a numpy array by using dict.items() method.

Here is the execution of the following given code

Python dictionary of numpy array
Python dictionary of numpy array

In this Python tutorial, we have discussed the Python dictionary of lists. Here we have also covered the following examples:

  • Python dictionary of lists append
  • Python dictionary of lists get value
  • Python dictionary of lists to dataframe
  • Python dictionary of lists to CSV
  • Python dictionary of lists iterate
  • Python dictionary of lists to list of dictionaries
  • Python dictionary of lists to Json
  • Python dictionary of lists access
  • Python dictionary of lists example
  • Python dictionary of lists sort
  • Python dictionary list all keys
  • Python dictionary list of Keys and values
  • Python dictionary list of tuple
  • Python dictionary with list comprehension
  • Python dict with list append
  • Python dict with list items
  • Python dict in list remove duplicate
  • Python dictionary of two lists
  • Python dictionary list update
  • Python dictionary list index
  • Python dictionary of lists get all values
  • Python dictionary list value append
  • Python dictionary vs list
  • Python filter dictionary list by value
  • Python dictionary of numpy array