nocnoc
nocnoc

Reputation: 361

TypeError when trying to iterate and compare values in a list and dict

I am trying to iterate over a list that is an import of a json and a dict where I want to store the values of the list in the value place. The problem is that when I loop over the list and do a comparative if statement I get this error message

if i["service"] == serviceIp[i]:
TypeError: unhashable type: 'dict'

The dict where I would like to store the addresses for the services

serviceIp = {
    "service-A": "",
    "service-B": ""
}

The list import from json which includes all the addresses

serviceAddress

[{'service': 'service-A', 'address': ['localhost1']}, {'service': 'service-B', 'address': ['localhost2']}] 

This is my loop and if statement

for i in serviceAddress:
        if i["service"] == serviceIp[i]:
            

Any idea what is causing this error? My goal is to compare the keys for service and store the service values into the values of the dict

Upvotes: 0

Views: 48

Answers (1)

Svw
Svw

Reputation: 63

i value in the for loop is a dict. ex: {'service': 'service-A', 'address': ['localhost1']} and can't be used as keys for dict.

If you want to store addresses for service names in dict you can do this:

for s in serviceAddress:
    serviceIp[s["service"]] = s["address"]

Or if you wan't to make sure to only add services that their names are already in the serviceIp dict:

for s in serviceAddress:
    if s["service"] in serviceIp:
       serviceIp[s["service"]] = s["address"]

Upvotes: 1

Related Questions