I found this Python code in our project:
data = {...}
devices = get_devices()
if len(devices) > 0:
data["first_device"] = devices[0]
if len(devices) > 1:
data["second_device"] = devices[1]
if len(devices) > 2:
data["third_device"] = devices[2]
if len(devices) > 3:
data["fourth_device"] = devices[3]
if len(devices) > 4:
data["fifth_device"] = devices[4]
It retrieves a bunch of devices, and adds them to an existing dict. I removed this code and replaced it with this one:
data = {...}
devices = get_devices()
labels = ["first_device", "second_device", "third_device", "fourth_device", "fifth_device"]
data.update(dict(zip(labels, devices)))
It takes advantage of two characteristics of the zipped list:
- It iterates up to the length of the shortest list.
- Two zipped lists can easily be turned into a dict.
No comments:
Post a Comment