-2

I have a dictionary of stock data like below:

{'_id': ObjectId('5ed25b3a4893efeab4cef4b3'),
 'time': 1286699400000.0,
 'open': 1128.0,
 'high': 1128.0,
 'low': 1128.0,
 'close': 1128.0,
 'volume': 100}

And tried to convert it to a list/array of data with the following code, but it only works for 1 item of dictionary. I don't know how to iterate over dictionaries?

def dict_to_array(data):
    training_set1 = []
    training_set1.append(data["open"])
    training_set1.append(data["high"])
    training_set1.append(data["low"])
    training_set1.append(data["close"])
    training_set1.append(data["volume"])
    training_set1 = np.array(training_set1).T
    return training_set1

EDIT: I like to have training_set1 as the result like:

[[o1, h1, l1, c1, v1],
 [o2, h2, l2, c2, v2],
 ...
 [on, hn, ln, cn, vn]]

EDIT2: I added data = data.values() to my code like below:

def dict_to_array(data):
    data = data.values()
    training_set1 = []
    training_set1.append(data["open"])
    training_set1.append(data["high"])
    training_set1.append(data["low"])
    training_set1.append(data["close"])
    training_set1.append(data["volume"])
    training_set1 = np.array(training_set1).T
    return training_set1

But I get the following error:

TypeError: 'dict_values' object is not subscriptable
Hasani
  • 3,543
  • 14
  • 65
  • 125
  • 2
    `print(list(data.values()))` gives you all values of the dict (converted to a list). Is that what you are looking for? – Ronald Jul 24 '20 at 18:18
  • 1
    You can use `dict.values()` to get values and `dict.items()` to get key-value pairs. – michalwa Jul 24 '20 at 18:19
  • 1
    Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – Jim G. Jul 24 '20 at 18:26

3 Answers3

1

This is the way to iterate over a dictionary, you can use the key var for each of the keys in a dictionary and value variable will contain their respective values for that key.

dictionary = {'name': "John Doe", 'age': 34, 'company': "abc ltd"}

for key, value in dictionary.items():
    print(f"{key} has {value} in dictionary")
  • Or: `for key in dictionary: print(f"{key} has {dictionary[key]} in dictionary")` – Red Jul 24 '20 at 18:40
0

Her is how you can use dict.items() and list():

dct = {'_id': '5ed25b3a4893efeab4cef4b3',
       'time': 1286699400000.0,
       'open': 1128.0,
       'high': 1128.0,
       'low': 1128.0,
       'close': 1128.0,
       'volume': 100}

def dict_to_array(data):
    return list(data.items())
Red
  • 26,798
  • 7
  • 36
  • 58
0

Use name.values() or list(name.values()) to get only values,

Use name.items() or list(name.items)) to get a list of tuples where each tuple is a key and value pair (0 key, 1 value).

12ksins
  • 307
  • 1
  • 12