How to Convert Python Dict to an Array [6 Examples ]

In this Python article, I will explain how to convert Python dict to an array with the most appropriate method present with examples.

To convert the Python dict to an array, we can use the np.array() function or array.array() function. Whether we want an array of the Python dictionary values, keys, or both as a key-value pair in Python, we can achieve it by using different functions like values(), keys(), and items() respectively with the array() function from both libraries.

Python Dict to an Array

Before knowing how to convert Python dict to an array, we should know what is meant by the terms used:

Python Dictionary: Also known as “Python dict”. A Python dictionary is an unordered data collection in a key-value pair format.

company = {"Apple": 5, "Facebook": 3, "Microsoft": 2}

Python NumPy Array: Unlike lists, NumPy arrays are homogeneous, meaning all elements are of the same type, a key feature that makes them suitable for mathematical operations.

import numpy as np

company = np.array(["Apple", "Facebook", "Microsoft"])

Now, let’s see some examples of how to convert a Python dict to an array:

Case 1: Python dict to array of values

To get only the Dictionary values to be stored or converted into an Array in Python NumPy, we can use the dict.values() function.

READ:  np.where in Pandas Python [4+ Examples]

The dict.values() function returns a list of all the values from the dictionary in Python. And, we will convert the list into an array using np.array type casting method.

import numpy as np

state_capitals = {
    "California": "Sacramento",
    "Texas": "Austin",
    "Florida": "Tallahassee",
    "New York": "Albany",
    "Illinois": "Springfield"
}

values_array = np.array(state_capitals.values())
print(type(values_array))

Output: The type() function confirms that the dictionary is converted into an array in Python.

<class 'numpy.ndarray'>
Python dict to an array

This way we can use the values() function with the np.array to convert a dictionary to array in Python.

Case 2: Python dict values to array

We can also use the list() function to create a list of dictionary values.

Note: The only difference between using and not using the list() function in Python is that the values() method of a dictionary returns a view object that displays a list of all the values in the Python dictionary. Wrapping this with list() converts it into a standard Python list.

import numpy as np

state_capitals = {
    "California": "Sacramento",
    "Texas": "Austin",
    "Florida": "Tallahassee",
    "New York": "Albany",
    "Illinois": "Springfield"
}

values_array = np.array(list(state_capitals.values()))
print(type(values_array))

Output: The implementation of the code is given below:

<class 'numpy.ndarray'>
dict to array python

This way we can use the list function with the np.array() function to convert the Python dict to an array.

Case 3: Convert dict to array Python only keys

To get only the Dictionary keys to be stored or converted into an Array in Python NumPy, we can use the dict.key() function.

The keys() method of a dictionary returns a view object that displays a list of all the values in the Python dictionary.

import numpy as np

average_temperatures = {
    "Miami": 77.0,
    "Denver": 50.9,
    "Seattle": 52.0,
    "Atlanta": 61.4,
    "Boston": 52.7
}

keys_array = np.array(list(average_temperatures.keys()))
print(type(keys_array))

Output: After the implementation of the Python code, the output we get is:

<class 'numpy.ndarray'>
python convert dict to array

This way we can use the np.array() with the keys() function to convert the Python dict to an array.

READ:  Attributeerror: Module 'keras.optimizers' has no attribute 'rmsprop'

Case 4: Python dictionary to array

If both keys and values are essential, we can convert them into a structured NumPy array using the dict.items() function in Python.

The dict.items() function returns a Python list of tuples of key values of the dictionary.

import numpy as np

city_zip_codes = {
    "Los Angeles": 90001,
    "Chicago": 60601,
    "Houston": 77001,
    "Phoenix": 85001,
    "Philadelphia": 19101
}

np_structured_array = np.array(list(city_zip_codes.items()))
print(type(np_structured_array))

Output: The implementation of the code is given below:

<class 'numpy.ndarray'>
dictionary to array python

The items() function with the numpy array() function, can be used to convert Python dict to an array.

Case 5: How to convert a dictionary to a 2D array in Python

Here, is how we can convert a Python dict to an array of 2 dimensions.

import numpy as np

presidents_terms = {
    "George Washington": [1789, 1797],
    "Abraham Lincoln": [1861, 1865],
    "Theodore Roosevelt": [1901, 1909],
    "John F. Kennedy": [1961, 1963],
    "Barack Obama": [2009, 2017]
}

two_d_array = np.array(list(presidents_terms.values()))
print(np.ndim(two_d_array))
print(type(two_d_array))

Output: To check the array dimension we can use the np.ndim() function in Python.

2
<class 'numpy.ndarray'>
dictionary to 2d array python

This way we can convert a Python dict to an array of 2nd dimension.

Case 6: Convert dictionary to array Python using array library

We can simply use the Python array library’s array() function to convert the dictionary into an array in Python.

The array module requires specifying a type code that defines the type of elements in the array. For example, ‘i‘ for integers, ‘f‘ for floating-point numbers, etc.

from array import array

inventory = {
    "TV": 399.99,
    "Laptop": 1099.99,
    "Smartphone": 699.99
}

arr = array('f', inventory.values())
print(type(arr))

Output: The implementation of the code is given below with a screenshot:

<class 'array.array'>
dict to array in Python

Conclusion

Converting Python dict to an array, expands the possibilities for data manipulation and analysis, leveraging the power of NumPy’s efficient array operations. We have seen different use cases like using items(), values(), and keys() function with the np.array() function, etc in detail.

READ:  Matplotlib subplots_adjust

Now, the choice of the case depends on what the Python problem needs.

You may like to read: