AppDividend
Latest Code Tutorials

How to Convert Python Dictionary to Array

0

Numpy has the capability to manipulate the array, access data, split the data, reshape, join the array, and subarray. The array object in Numpy is called ndarray.

Python Dictionary to Array

To convert Python dictionary to array, you need to follow the three steps.

  1. Use dict.items() method to get key-value pair view object.
  2. Use the list() method to convert it into a list.
  3. Use numpy.array() method to convert a list into an array.

Step 1: Get a key-value pair view object.

Python dictionary items() is an inbuilt function used to get all the keys and associated values with those keys. The dict.items() method returns the collection of the key-value pairs in the dictionary.

sabrina = {
    "witch": "Sabrina Spellman",
    "warlock": "Nicholas Scratch",
    "darklord": "Lucifer Morningstar",
}

data = sabrina.items()
print(data)

Output

dict_items([('witch', 'Sabrina Spellman'), ('warlock', 'Nicholas Scratch'), 
            ('darklord', 'Lucifer Morningstar')])

And we get the view object of the dictionary.

Step 2: Use list() method

The list() constructor in Python returns a list. The list() function takes the view object as a parameter and returns the list.

sabrina = {
    "witch": "Sabrina Spellman",
    "warlock": "Nicholas Scratch",
    "darklord": "Lucifer Morningstar",
}

data = sabrina.items()
list = list(data)
print(list)

Output

[('witch', 'Sabrina Spellman'), ('warlock', 'Nicholas Scratch'), 
 ('darklord', 'Lucifer Morningstar')]

And we get the list of tuples that contains two items: key and value of the dictionary.

If no parameters are passed, it returns an empty list.

Step 3: Use numpy.array() method

To convert a list to an array in Python, use the numpy.array() method. The np.array() method creates a numpy ndarray object by using the array() function.

To work with numpy, you need to install the numpy and import it into our program. Then use the np.array() function.

import numpy as np

sabrina = {
    "witch": "Sabrina Spellman",
    "warlock": "Nicholas Scratch",
    "darklord": "Lucifer Morningstar",
}

data = sabrina.items()
list = list(data)
arr = np.array(list)
print(arr)

Output

[['witch' 'Sabrina Spellman']
 ['warlock' 'Nicholas Scratch']
 ['darklord' 'Lucifer Morningstar']]

And we passed the list object to the np.array() function, which returns the array. Finally, we converted from Python dictionary to array.

See also

Python Dictionary to List

Python Dictionary to DataFrame

Python Dictionary to CSV

Python Dictionary to String

Python Dictionary to JSON

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.