Home>

Thank you for viewing.
I asked the question earlier, and answered about obtaining the value after sorting the keys in the dictionary.
I couldn't ask a specific question about what I couldn't solve, so I asked again.
https://www.tutorialfor.com/go.php?id=143402

What I want to do is to store a list of sorted dictionary keys in a two-dimensional array numpy and output the dictionary value corresponding to this key.
Specifically, the program only knows how to write halfway

import pandas as pd
import numpy as np
dic_list = ()
df_1 = pd.DataFrame ([[1, 1], [1, 1]])
df_2 = pd.DataFrame ([[2, 2], [2, 2]])
df_3 = pd.DataFrame ([[3, 3], [3, 3]])
df_4 = pd.DataFrame ([[4, 4], [4, 4]])
dic = {'a': df_1, 'c': df_2, 'b': df_3, 'd': df_4}
sorted_keys = sorted (dic)
np_dic_keys = np.array ([[sorted_keys [0], sorted_keys [1]], [sorted_keys [2], sorted_keys [3]]])
print (np_dic_keys)
# np_dic_keys_2 = np.array ([[dic [sorted_keys [0]], dic [sorted_keys [1]]], [dic [sorted_keys [2]], dic [sorted_keys [3]]]])
#print (np_dic_keys_2) Different results than expected


I would like to change the key stored in np_dic_keys to the corresponding dic value.
The result is the current np_dic_keys
[['a''b']
['c''d']]
Is the data frame of the corresponding dictionary
[[1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4]]
I hope to make it like this.

In addition to the proposed solution, I would appreciate it if you could tell me any suggestions or ideas in the current program.

  • Answer # 1

    How about this

    np_dic_keys_2 = np.vstack ((np.hstack ((dic [sorted_keys [0]]. values,
                                          dic [sorted_keys [1]]. values)),
                               np.hstack ((dic [sorted_keys [2]]. values,
                                          dic [sorted_keys [3]]. values))))
    print (np_dic_keys_2)