7

I am trying to convert the dictionary

{0: {0: 173, 1: 342, 2: 666, 3: 506, 4: 94},
 1: {0: 13, 1: 2171, 2: 1915, 3: 3075, 4: 630},
 2: {0: 0, 1: 265, 2: 5036, 3: 508, 4: 11},
 3: {0: 0, 1: 3229, 2: 2388, 3: 3649, 4: 193},
 4: {0: 3, 1: 151, 2: 591, 3: 1629, 4: 410}}

to numpy array

array([[ 173,  342,  666,  506,   94],
       [  13, 2171, 1915, 3075,  630],
       [   0,  265, 5036,  508,   11],
       [   0, 3229, 2388, 3649,  193],
       [   3,  151,  591, 1629,  410]])

Any ideas how to do it efficiently?

3
  • 1
    Efficient in terms of what? Speed, memory, cpu-cycles, readability, etc? Commented Jan 3, 2019 at 11:10
  • readibility mostly, speed and memory are on second place Commented Jan 3, 2019 at 11:17
  • 1
    np.array([list(inner_dict.values()) for inner_dict in d.values()]) Commented Jan 3, 2019 at 11:23

1 Answer 1

8

A Python-level loop is unavoidable here, so you can use a list comprehension:

res = np.array([list(item.values()) for item in d.values()])

# array([[ 173,  342,  666,  506,   94],
#        [  13, 2171, 1915, 3075,  630],
#        [   0,  265, 5036,  508,   11],
#        [   0, 3229, 2388, 3649,  193],
#        [   3,  151,  591, 1629,  410]])

As per @FHTMitchell's comment, this assumes your dictionary items (inner and outer) are ordered appropriately. Dictionaries are insertion ordered in 3.6 as a CPython implementation detail, and officially in 3.7+.

One way to define an order for inner and outer dictionaries is via operator.itemgetter:

getter = itemgetter(*range(5))
res = np.array([getter(item) for item in getter(d)])

Such a solution does not depend on the order of your input dictionary.

Sign up to request clarification or add additional context in comments.

1 Comment

nb this only works in python 3.6 or later and only if your dictionaries are constructed such that they are ordered.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.