0

I want to store two values from JSON_file in new dict like this : {[1,2,5]:[0], [1,2,4]:[2]}

my JSON-file looks like this :

{
    "index": [
        {
            "timestamp": "2018-04-17 17:56:25",
            "src": "src",
            "dst": [1,2,5],
            "value": [0],
            "datatype": "datatype"
        },
        {
            "timestamp": "2018-04-17 18:00:43",
            "src": "src",
            "dst": [1,2,4],
            "value": [2],
            "datatype": "datatype"
        }
   ]
}

I wrote this code:

with open(filename) as feedjson:
    json_data = json.load(feedjson)
    feedjson.close()

list_dev = {}
for i in json_data["index"]:
    key = i['value']
    value = i['dst']
    list_dev[key] = value
print(list_dev)

I get this error:

list_dev.update({key: value})
TypeError: unhashable type: 'list'

can someone help me to fix this problem please?

AhmyOhlin
  • 519
  • 4
  • 8
  • 18

2 Answers2

1

This is just for understanding purposes:

Dictionary keys should be immutable as explained here. In the question, [1,2,5] is a list which are mutable(contents can be modified with methods like append,pop, push) data types. So, the only way to use the entire contents of a list as a dictionary key(highly unusual) is to convert it to an immutable data type such as a tuple or string:

new_dict = {}              #initialize empty dictionary

dst = t['index'][0]['dst']      #[1,2,5]
value = t['index'][0]['value']  #[0]

new_dict[tuple(dst)] = value  #new_dict key "dst" as tuple

print(new_dict)     
--->{(1, 2, 5): [0]}

new_dict[str(dst)] = value  #new_dict key "dst" as string

print(new_dict)      
---->{'[1, 2, 5]': [0]}
amanb
  • 5,276
  • 3
  • 19
  • 38
0

value is a list -> [1] or [2] or whatever, list is mutable object so you can't hash it

you can use the element in the list like key=i['value'][0] or convert the list to tuple like key=tuple(i['value']) both objects are immutable thus can be hashed and used as a key

by the way with provide context manager so you don't need to close the file using feedjson.close(), with will do it for you

shahaf
  • 4,750
  • 2
  • 29
  • 32
  • Thank your for the answer. key=i['value'][0] i cant use this because i have a long JSON file.When I convert list to tuple key=tuple(i['value']) i get this error: TypeError: 'int' object is not iterable – AhmyOhlin Apr 17 '18 at 22:41
  • @AhmyOhlin what are the different types of data that can appear under `value` field? – shahaf Apr 17 '18 at 22:47
  • Value can be just integers – AhmyOhlin Apr 17 '18 at 22:50
  • I fixed it by converting value to data of type "string" value = str(i['value']) key = str(i['dst']). Modify your answer from tuple to string please. Thanks for the help – AhmyOhlin Apr 17 '18 at 22:53
  • 1
    Your example shows Value being a list, not an integer. The immutable version of a list is a tuple. I see nothing wrong with his answer. – Mantas Kandratavičius Apr 17 '18 at 22:55