In this Python tutorial, we will discuss about Python convert dictionary to an array. Here we will also cover the below examples:
- Python convert dictionary to numpy array
- Python convert dictionary to byte array
- Python convert dictionary values to array
- Python convert dictionary to 2d array
- Python convert dictionary keys to array
- Python convert array of dictionary to dataframe
- Python convert dictionary to json array
Python convert dictionary to an array
- Let us see how to convert a dictionary to an array in Python
- Python provides an easy built-in function to perform this particular task. There is a various method to perform this operation.
- By using dict.items() method
- By using numpy.array() method
- By using the combination of numpy.array() and dict.items() method
By using dict.items()
In Python to return a combination of the key-value elements in a dictionary, we can use the dict.items() method. In this example, we can use this method in the list() as an argument this method helps the user to convert the dictionary into a list.
Syntax:
Here is the Syntax of dict.items() method
dictionary.items()
Note: This method does not take any argument. It returns an object as a list with contains key-value pair elements from a dictionary.
Example:
Let’s take an example and check how to convert a dictionary to an array by using dict.items() method
import numpy as np
new_dictionary = {"Micheal": 18, "Elon": 17}
new_lis = list(new_dictionary.items())
con_arr = np.array(new_lis)
print("Convert dict to arr:",con_arr)
In the above code first, we will import a numpy module. Now create a dictionary and use numpy.array() method to convert a dictionary to an array.
Here is the Screenshot of the following given code
By using numpy.array()
In Python, if we want to convert a dictionary to an array then this method will you to perform this operation.
Syntax:
Here is the Syntax of numpy.array()
numpy.array(
object,
dtype=None,
copy=True,
order='K',
subok=False,
ndim=0,
like=None
)
- It consists of few parameters:
- Object: An object or item whose method always returns a numpy array.
- dtype: If the datatype is not given in the parameter then it will be determined as the minimum type.
- Copy: It is an optional parameter and if the object is a nested sequence then it satisfies any other requirement.
- Order: In this case if the object is not in an array then it will be a ‘C’ order. If F and C order is preserved then it will be a ‘K’ order.
- ndim: It is an optional parameter and specifies the minimum number of dimensions.
- Return: It will return an object which contains the number of elements.
Example:
import numpy as np
my_new_dict = {15: 'oliva',
18: 'Hayden',
19: {'n': 'George',
'z': 'China',
'p': 'Egypt'}
}
new_val = my_new_dict.items()
elemen = list(new_val)
con_arr = np.array(elemen)
print(con_arr)
In the above code first, we will declare a nested dictionary and contains key-value pair elements. Now use numpy.array() method and pass ‘elemen’ variable as an argument after that print the result and it will display the three-dimensional array.
Here is the execution of the following given code
By using the combination of numpy array and list comprehension method
In this example, we have used the concept of the list comprehension method along with the numpy array.
Source Code:
import numpy as np
from ast import literal_eval
new_str = """{
"student_info": {"stu_name": "George",
"last_nam": "lucid", "skills": "Python"},
"student_info2": {"stu_name": "Oliva",
"last_nam": "xender", "skills": "Java"},
"student_info3": {"stu_name": "cravy",
"last_nam": "lucifier", "skills": "sql"},
"student_info2": {"stu_name": "Elon",
"last_nam": "Mathew", "skills": "Mongodb"},
}"""
n = literal_eval(new_str)
out_arr = np.array([[new_val[z] for z in ['stu_name', 'last_nam',
'skills']] for key, new_val in n.items()])
print("Convert dict to array:",out_arr)
print(type(out_arr))
In the above code first, we import a ‘literal_eval’ library and then create a class of new strings. In Python, the ‘literal_eval’ method helps the user to convert string type to a dictionary. Now we want to convert a dictionary to an array so we can use numpy.array() method.
Here is the Output of the following given code
Read: Python dictionary of tuples
Python convert dictionary to numpy array
- Here we can see how to convert a dictionary into a numpy array.
- In this example we can apply the concept of structured array. In Python the structured array contains data of same type which is also known as fields. Here ‘new_values’ is a dictionary which contains key-value pair. Now create a ’emp_info’ variable whose datatype is a structure with two fields.
Source Code:
import numpy as np
new_values = {16:2.33, 19: 3.4456, 8: 199.9, 117: 172.89}
emp_info = ['emp_id','information']
new_format = ['f8','f8']
dtype = dict(names = emp_info, formats=new_format)
con_arr = np.array(list(new_values.items()), dtype=dtype)
print(repr(con_arr))
Here is the execution of the following given code
Another example to convert a dictionary into a numpy array
Example:
import numpy as np
my_dict = {12: 14, 15: 18, 25: 89, 13: 99,
78: 25, 19: 416, 17: 189}
converted_arr = np.array(list(my_dict.items()))
print(converted_arr)
Here is the Screenshot of the following given code
Read: Get all values from a dictionary Python
Python convert dictionary to byte array
- Let us see how to convert Python dictionary to byte array.
- In Python the byte array object allows us to change its elements which are available in the dictionary. It is a mutuable sequence of integers within the range of 0 to 256.
Syntax:
bytearray
(
source,
encoding,
errors
)
- It consists of few parameters.
- Source: To convert an iterable into a byte array.
- encoding: It is an optional parameter and encoding of the string will execute if the given iterable sequence is a string.
Source Code:
import json
my_new_dictionary = {'stu_name': 'Brenda', 'code': 'dr-02'}
user_info = json.dumps(my_new_dictionary, indent=3).encode('utf-8')
print(user_info)
Here is the Screenshot of the following given code
Read: Python creates a dictionary from two lists
Python convert dictionary values to array
In this example, I have a dictionary with ‘values’ variables as keys and a list of integers as values. Now I am going to convert the lists into a numpy array and modify the dictionary by using the dict comprehension method.
Source Code:
import numpy as np
def new_arr(dictionary):
return {new_k:np.array(new_v) for new_k, new_v in dictionary.items()}
my_dict = {
'val1': [789, 156, 178, 198],
'val2': [872, 199, 156, 189],
'val3': [100, 1345, 190, 167]
}
print("Convert values into arr",new_arr(my_dict))
Here is the implementation of the following given code
Read: Python dictionary pop
Python convert dictionary to 2d array
- Let us see how to convert a dictionary to a 2-dimensional array.
- To perform this task we can use the combination of list comprehension and numpy.array() method.
- In this example the inner comprehension for i in ‘new_keys’ is going to iterate over the rows in ‘new_dict’ variable.
Example:
Here is some code that will declare a 2d array using the numpy module. Now we have to use a list of the keys in order because dictionaries do not store the key-value pair elements
import numpy as np
new_dict = {'George':(6,12,9,3), 'Micheal':(16,99,22,33)}
new_keys = ['George','Micheal']
new_2d_arr = np.array([new_dict[i] for i in new_keys])
print (new_2d_arr)
Here is the Screenshot of the following given code
Read: Python dictionary contains
Python convert dictionary keys to array
- Here we can see how to convert Python dictionary keys to an array.
- By using the loop()+zip()+map() function can be used to solve this problem. In this example, we will see how to convert dictionary key elements into an array.
- If we want to return a value from the map() function then we have to pass a method like set()[ to declare a set].
- In Python, the zip() method takes iterable items and returns an object in the form of a tuple and if no argument is available in the zip() method then it returns an empty iterator.
Source Code:
my_new_dict = {'k' : {},
'c' : {},
'd' : {},
'j':{}}
new_val = list(my_new_dict.values())
m = set()
for new_element in new_val:
for u in new_element:
m.add(u)
new_output = []
new_output.append(m)
for new_k, new_v in my_new_dict.items():
con_key = []
for u in m:
con_key.append(new_v.get(u, 0))
new_output.append(con_key)
new_output = [[u for u, new_v in my_new_dict.items()]] + list(map(list, zip(*new_output)))
print("Convert dict keys into arr : ",new_output)
In the above code first, we will initialize a dictionary and assign a key-value pair element. Now I declare a variable and use the list function to pass an original dictionary as an argument. After that create an empty list to store a keys element in it and for the list comprehension method, we can apply multiple methods as an argument.
Here is the execution of the following given code
Read: Python dictionary comprehension
Python convert array of dictionary to dataframe
- In Python to convert an array of dictionaries to a dataframe, we can easily use the function dict.items(). By using dict.items() to get a set like a dictionary with the key-value pairs.
- In this example, we created a dataframe by using the pandas library and then initialize a dictionary. Now use the list(iterable) method to convert an object into a list.
Let’s take an example and check how to convert dictionary array to dataframe.
Code:
import pandas as pd
my_dictionary = {'m': [17,31], 'p': [90,16], 'q': [78,116]}
v = pd.DataFrame(list(my_dictionary.items()))
print(v)
Here is the execution of the following given code
As you can see, the dictionary of the array got converted to pandas dataframe.
Alternative example to convert dictionary of an array into dataframe
By using index and column keywords we can easily perform this particular task
Example:
import pandas as pd
new_dict = [{'Micheal': 'value', 'John': 'value', 'oliva': 'values'},
{'adam':10, 'hayden': 20, 'George': 30}]
new_data = pd.DataFrame(new_dict, index =['ind1', 'ind2'],
columns =['val1', 'val2'])
new_data2 = pd.DataFrame(new_dict, index =['index1', 'index2'])
print ("Convert arr of dict to dataframe:",new_data2)
In this example, we will demonstrate how to create a pandas dataframe by lists of dictionaries. To do this we will initialize an element of lists with two-column indexes with the same values as a dictionary key.
Here is the implementation of the following given code
You may also like reading the following tutorials.
- Python dictionary find a key by value
- Python Dictionary Count + Examples
- Python convert dictionary to list
- Python dictionary remove
- Python Dictionary to CSV
- How to create an empty Python dictionary
- Python dictionary multiple keys
- Python dictionary popitem() method [With Examples]
In this Python tutorial, we have discussed about Python convert dictionary to an array. Here we have also covered the following topics:
- Python convert dictionary to numpy array
- Python convert dictionary to byte array
- Python convert dictionary values to array
- Python convert dictionary to 2d array
- Python convert dictionary keys to array
- Python convert array of dictionary to dataframe
- Python convert dictionary to json array
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.