Python has different types of data structures to manage your data efficiently. Lists are simple sequential data, whereas a dictionary is a key-value pair data. Both of them have unique usability and is already been implemented with various helpful methods. Many times, we need to convert the dictionary to a list in Python or vice versa. In this post, we’ll look at all possible methods to do so.
Dictionary to List Conversion can be done in multiple ways. The most efficient way to do it is, calling the helping methods of the dictionary. Some methods like, items(), values(), and keys() are useful in extracting the data from dictionary. Moreover, you can also loop through the dictionary to find individual elements.
What is a Dictionary in Python?
Dictionary is a data structure that stores the data as key-value formats. The order of elements is not reserved in the dictionary. When converting the dictionary data to the list, your order may change. Moreover, duplicates are not allowed in the dictionary.
Example –
d = {"name":"python", "version":3.9}
What is a List in Python?
List is a data structure that saves the values sequentially. Lists are termed as arrays in many other programming languages. In Python, lists have flexible lengths, and the elements inside them can be added or removed anytime. Unlike dictionaries, you can have duplicates in the list.
Example –
d = ["name", "python", "version", 3.9]
Converting Dictionary to List in Python
There are several ways of converting a dictionary to a list. We’ve tried our best to ensure that we cover the maximum methods possible. If you have any other method, please let us know in the comments.
1. Dictionary to List Using .items() Method
.items()
method of the dictionary is used to iterate through all the key-value pairs of the dictionary. By default, they are stored as a tuple (key, value) in the iterator. Using list()
will get you all the items converted to a list.
Code:
d = {"name":"python", "version":3.9}
new_list = list(d.items())
print(new_list)
Output:
[('name', 'python'), ('version', 3.9)]
2. Using .keys() Method
.keys()
method gets you all the keys from the dictionary. Combining it with the list() function, you’ll get a list of all keys from the dictionary.
Tip: If you use .keys() and .values() method of the dictionary, make sure you don’t alter the dictionary in between. Otherwise, the sequence from key and value would mismatch.
Code:
d = {"name":"python", "version":3.9}
new_list = list(d.keys())
print(new_list)
Output:
['name', 'version']
3. Using .values() Method
.values()
method from dictionaries can be used to get a list of values. Using list()
function, we can convert values to a list.
Code:
d = {"name":"python", "version":3.9}
new_list = list(d.values())
print(new_list)
Output:
['python', 3.9]
4. Dictionary to List using loop + items() Method
Append is a method in python lists that allows you to add an element to the end of the list. By initializing empty elements and then looping through the dictionary.items()
, we can append a new list [key, value] in the original list.
Code:
d = {"name":"python", "version":3.9}
new_list = []
for key, val in d.items():
new_list.append([key, val])
print(new_list)
Output:
[['name', 'python'], ['version', 3.9]]
5. List Comprehension Method
List Comprehension is easy of initializing a list in python. Moreover, you can choose the value of elements in the same single line. Using dictionary.items()
to fetch the key and values of the items, and then adding them to the list.
Code:
d = {"name":"python", "version":3.9}
new_list = [(k, v) for k, v in d.items()]
print(new_list)
Output:
[('name', 'python'), ('version', 3.9)]
6. Using Zip Function
The zip function is a useful way of combining two lists/iterators. This way we can combine .keys()
and .values()
methods of the dictionary to get both the values simultaneously.
Code:
d = {"name":"python", "version":3.9}
new_list = zip(d.keys(), d.values())
new_list = list(new_list)
print(new_list)
Output:
[('name', 'python'), ('version', 3.9)]
7. Dictionary to List Using Iteration Method
Iteration is always your friend if you’re unaware of any methods of dictionaries. You can fetch the key by looping through the dictionary and once you have the key, you can use dictionary[key]
to fetch its value. Following code uses a similar technique along with .append()
function to push elements into a list.
Code:
d = {"name":"python", "version":3.9}
new_list = []
for i in d:
k = [i, d[i]]
new_list.append(k)
print(new_list)
Output:
[['name', 'python'], ['version', 3.9]]
8. Dictionary to List using Collection Method
You can create a named tuple in python by using collections.namedtuple()
. This way you can declare a custom data structure along with a list of its members. In this case, we’ve used “name” and “value” to be its member.
Code:
import collections
d = {"name":"python", "version":3.9}
list_of_tuple = collections.namedtuple('List', 'name value')
new_list = list(list_of_tuple(*item) for item in d.items())
print(new_list)
Output:
[List(name='name', value='python'), List(name='version', value=3.9)]
9. Using Map Function
map() is an inbuilt function that maps any function over an iterator/list. You can map the list() function over all the elements of d.items() to convert them into lists of lists. The following example will help you understand –
Code:
d = {"name":"python", "version":3.9}
new_list = list(map(list, d.items()))
print(new_list)
Output:
[['name', 'python'], ['version', 3.9]]
Difference between Lists and Dictionary
Lists | Dictionary |
Lists are collection of values like arrays. | Dictionary is a structure of key and value pairs |
Lists are written inside [ ] ans separated by ‘ , ‘ . | Dictionary are written inside { } is {key : value} and each pair is separated by ‘ , ‘ . |
The index of integers in lists start from 0. | The keys can be of any type. |
Index is used to access elements. | Elements are accessed by key-values. |
The order remains same unless changed by user. | No specific order maintained. |
Dictionary to List of Tuples Python
You create a dictionary using the dict method mostly. If you want to obtain the output as a list of tuples, we can get the dictionary elements using the items method. We can use list comprehension instead of loops to make the code look less complex.
Example:
dictA = { 'Python': 9, 'Problems: 6, 'Project': 11 }
# change a dict into list of tuple
list = [(i, j) for i,j in dictA.items()]
print(list)
Python Dictionary to List by Key
Using the keys function of the dictionary, we can change the dictionary contents into a list data type. This can be easily comprehended with the help of this example:
dictA = {'A':14, 'D':16, 'I':18, 'N':10}
listA = list(dictA.keys())
print(listA)
print (type(listA))
#Output:
['A', 'D', 'I', 'N']
<class 'list'>
Get Dictionary Values to List Python
dictA = {'A':14, 'D':16, 'I':18, 'N':10}
listA = list(dictA.values())
print(listA)
print (type(listA))
#[14, 16, 18, 10]
<class 'list'>
* empty string python add
str1 = ""
str1 = str1 + "add new string"
print(str1)
#add new string
* empty string python boolean
If you declare an empty string in Python, the interpreter will assign False Boolean value to the string.
s = ""
print(bool(s))
# output: False
You will get True as the output only if the string is non empty.
Dictionary to List – FAQs
In the dictionary, to get a value you have to provide its key. dictionary[key] is the correct syntax of getting a value from the dictionary for any key ‘key_item’. If you provide an incorrect key, it’ll throw KeyError.
dictionary = {} is the syntax to create an empty dictionary. Use two curly brackets to initialize an empty dictionary.
Map dictionary.get() over the list to get a list of values. map(dic.get, lst) is the correct syntax to do it.
Use the append() method of the list to add a dictionary to the list. Append ensure that you add a dictionary at the end of the list every time. Example –
x = []
x.append({“v”: 5})
See Also
Conclusion
Lists and dictionary are inter-changeable in python which comes very handy to the coders. Above are some of the ways that might help you in times of difficulty. Hope it helped.