简体   繁体   中英

How to automate extraction of values represented by numpy array associated with keys as separate data from a dictionary

I have a python dictionary that contains values that are saved within multiple numpy arrays for each key. I want to extract the values from each key in an automated way rather than individually go through each key to extract the values with for instance dictname[key1], dictname[key2], etc.

I have tried 'for' loops, but that is not working and being a beginner I can't work out where I am going wrong. See below:

type(Win_mapping) = class 'collections.defaultdict'

keys list :

Win_mapping.keys()

Out:
dict_keys([(3, 8), (2, 5), (2, 8), (1, 8), (2, 7), (3, 7), (3, 6), (2,   6), (1, 7), (1, 6), (1, 4), (0, 7), (6, 5), (3, 5), (4, 4), (4, 6)])

Example of some of the values for the first key

Win_mapping[(3, 8)]

Out:
[array([  0.00000000e+00,   6.33000017e-27,   1.73497305e-03,
     -8.36198378e-05,   2.74863690e-01], dtype=float32),
 array([  0.00000000e+00,   6.33999998e-27,   1.19663752e-03,
     -2.99715757e-05,   2.62920409e-01], dtype=float32),
 array([  0.00000000e+00,   6.35000018e-27,   6.05389301e-04,
     -3.59380065e-05,   2.54130781e-01], dtype=float32),
 array([  0.00000000e+00,   6.36000000e-27,   3.28844151e-04,
     -8.31774960e-05,   2.48996541e-01], dtype=float32),
 array([  0.00000000e+00,   6.36999981e-27,   3.52510775e-04,
     -1.14181137e-04,   2.47686639e-01], dtype=float32)]

For loop example:

for key, value in Win_mapping:
    node_key = [value]
    print(node_key)

[8]
[5]
[8]
[8]
[7]
[7]
[6]
[6]
[7]
[6]
[4]
[7]
[5]
[5]
[4]
[6]

This is just a representation of the second number for each key eg (3, 8), (2, 5), etc.

The result I want is an automated method to extract the values within each key then at the same time, and I am not sure this is possible, using just the position of the key in the list rather than the keys name. This is because I am setting up code which will hopefully take in different dictionaries with different key names.

You need to use dict.items to access the key-value

Ex:

for key, value in Win_mapping.items():
    node_key = [value]
    print(node_key)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM