×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Dictionary keys and values to separate NumPy arrays

Learn, how to separate dictionary keys and values to create two separate NumPy arrays?
By Pranit Sharma Last updated : December 25, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a dictionary and we need to separate the keys and values into two numpy arrays.

Separate the dictionary keys and values to create two separate NumPy arrays

For this purpose, we can use the numpy.formiter() two times for keys and values respectively. This function creates a new 1-dimensional array from an iterable object. Inside this, we can pass the dict.keys() and dict.values() separately.

Below is the syntax of numpy.formiter():

numpy.fromiter(iter, dtype, count=-1, *, like=None)

Let us understand with the help of an example,

Python code to separate dictionary keys and values to create two separate NumPy arrays

# Import numpy
import numpy as np

# Creating a dictionary
d = {5.207: 0.699, 6.820: 0.080, 7.233: 0.103, 8.530: 0.018}

# Separating key and values in two arrays
key = np.fromiter(d.keys(), dtype=float)
vals = np.fromiter(d.values(), dtype=float)

# Display result
print("Key array:\n",key,"\n")
print("Value array:\n",vals,"\n")

Output

Example: Dictionary keys and values to separate NumPy arrays

Python NumPy Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.