Freya Haslam
Freya Haslam

Reputation: 1

Need to convert an array to a dictionary

I was given data to import and it imported as an array but I need it as a dictionary. It essentially imports as a dictionary just within an array and I don't know how to make it just an array.

I have tried replacing the '[' with ' ' but this hasn't worked and I'm sure theres a better way

I imported the data this way

stock = np.loadtxt("wh_stock.dat",dtype = dict)

Result was:

['{"01":' '115,' '"02":' '34,' '"03":' '350,' '"04":' '273,' '"05":'
 '922,' '"06":' '844,' '"07":' '575,' '"08":' '523,' '"09":' '179,'
 '"10":' '676,' '"11":' '825,' '"12":' '693,' '"13":' '632,' '"14":'
 '195,' '"15":' '692,' '"16":' '956,' '"17":' '619,' '"18":' '588,'
 '"19":' '580,' '"20":' '648}']   

I want it to be:

 {"01": 115, "02": 34, "03": 350, "04": 273, "05":
     922, "06": 844, "07": 575, "08": 523, "09": 179,
     "10": 676, "11": 825, "12": 693, "13": 632, "14":
     195, "15": 692, "16": 956, "17": 619, "18": 588,
     "19": 580, "20": 648}

Original data in .dat file:

{"01": 115, "02": 34, "03": 350, "04": 273, "05": 922, "06": 844, "07": 575, "08": 523, "09": 179, "10": 676, "11": 825, "12": 693, "13": 632, "14": 195, "15": 692, "16": 956, "17": 619, "18": 588, "19": 580, "20": 648}
there is probably a better way to import but this is all I have been taught

Upvotes: 0

Views: 73

Answers (2)

Richard Stoeffel
Richard Stoeffel

Reputation: 695

The python json library can help you out:

UPDATED

stock is actually being saved as a kind of space separated dataframe, NOT just a string (which it does look like). That being said, this is a pretty small dataset, so you can just join it together to treat it like a string:

import json

stock = np.loadtxt("wh_stock.dat", dtype=list)
data_str = "".join(stock)
json.loads(data_str) #json.loads will ensure its a dict object

additionally, if you do want integer keys as fuglede pointed out, you can type cast your dict keys:

int_keyed_stock = {int(key): val for key, val in json.loads(data_str).items()}

For sure not the most elegant solution, and im sure pandas can handle this better, but the dataset you have is tiny, so no need to go overboard

Upvotes: 2

monolith
monolith

Reputation: 1706

You have to specify structural type of data and formats in loadtxt function. '|S4' means 4-byte string.

a = np.loadtxt(d, dtype={'names': ('key', 'val'), 'formats':('|S4', np.int32)})
b = dict(map(lambda x: (x[0].decode('utf-8'), x[1]), a))

The first line will load the strings as byte data, e.g b'02', you can turn them into regular string type with decode function which takes a character set encoding.

Upvotes: 0

Related Questions