Elliot G
Elliot G

Reputation: 99

Creating dictionary from lists without overwriting

I'm trying to create a dictionary from 3 lists and I'm having trouble with the values being overwritten.

My lists look like this:

hosts = ["Host1", "Host2" ...]
uptime = ["50", "60" ...]
downtime = ["50", "40" ...]

I need a dictionary that looks like this:

{"availability": [{"Host": "Host1", "Uptime": "50", "Downtime": "50"}, {"Host": "Host2", "Uptime": "60", "Downtime": "40"}]}

Here's my code:

availability_json = {"availability": {}}

for x in range(len(hosts)):
  availability_json["availability"]["Host"] = hosts[x]
  availability_json["availability"]["Uptime"] = uptime[x]
  availability_json["availability"]["Downtime"] = downtime[x]

When I run it only the final list is included. I've also tried with dict comprehension with the same issue.

Upvotes: 0

Views: 122

Answers (2)

mkrieger1
mkrieger1

Reputation: 23246

Your mistake is that you want to collect multiple instances of "availability", but you created a data structure that can hold only one of them.

You need a list. You even acknowledged this yourself,

I need a dictionary that looks like this:

{"availability": [{...}, {...}]}

where [ ... ] is the list. But in your code, you didn't create a list.

The adjustments you need to make in your code are:

  1. initialize a dictionary containing a list, instead of a dictionary containing a dictionary

  2. in every iteration of the loop, create a new "availability" dictionary (instead of reusing the same one each time), and append it to the list

availability_json = {"availability": []}  # 1.

for x in range(len(hosts)):
  a = {}  # 2.
  a["Host"] = hosts[x]
  a["Uptime"] = uptime[x]
  a["Downtime"] = downtime[x]
  availability_json["availability"].append(a)

Of course, Python allows you to write the same more succinctly, as shown in orlp's answer.

Upvotes: 1

orlp
orlp

Reputation: 117771

What you want is:

availability_json = {
    "availability": [
        {"Host": host, "Uptime": up, "Downtime": down}
        for host, up, down in zip(hosts, uptime, downtime)
    ]
}

Upvotes: 2

Related Questions