I have a list of equipment software, and I'm trying to make a dictionary with the key being the name of the software and value an array of all versions to this key.
Equipment software list format
[
[
{"name": "openjdk-8-jre", "version": "8u171-b11-1~deb9u1"},
{"name": "python2.7", "version": "2.7.13"},
{"name": "npm", "version": "8.0.0"},
],
[
{"name": "openjdk-8-jre", "version": "8u171-b11-1~deb9u1"},
],
[
{"name": "python2.7", "version": "2.7.13"},
{"name": "npm", "version": "7.0.0"},
],
]
What I'm trying:
softwares = {}
for software in all_equipment_softwares:
softwares[software] = []
for equipment in equipments_dump:
for software in equipment["softwares"]:
software_name = software["name"]
software_version = software["version"]
softwares[software_name].append(software_version)
What I'm getting:
[
{"openjdk-8-jre": ["8u171-b11-1~deb9u1", "8u171-b11-1~deb9u1"]},
{"python2.7": ["2.7.13", "2.7.13"]},
{"npm": ["8.0.0", "7.0.0"]},
]
I've been trying to break my head for hours, but I can't get the expected result
The expected result:
[
{"openjdk-8-jre": ["8u171-b11-1~deb9u1", "8u171-b11-1~deb9u1", None]},
{"python2.7": ["2.7.13", None, "2.7.13"]},
{"npm": ["8.0.0", None, "7.0.0"]},
]
How can I add a null value in the values of a given key when the software is not present on that equipment?
CodePudding user response:
software_version = software["version"]
Your question was a bit vague.
I assume the above blows up with KeyError
when the software is not present on that equipment.
Use:
software_version = software.get("version")
Also, please RTFM: https://docs.python.org/3/library/stdtypes.html#dict.get
CodePudding user response:
Here's an approach you could use to get an output with a single dictionary, instead of a list of dictionaries. The key insight is to prepopulate the value with a list of None. Feel free to ask for any clarifying questions.
softwares = {}
softwares_length = len(all_equipment_softwares)
#iterate through each software_list of all_equipment_softwares
for count, software_list in enumerate(all_equipment_softwares):
#iterate through each software of software_list
for software in software_list:
#if it's a software we haven't seen add it to our dictionary with an array full of None based on the length of all_equipment_softwares
if software['name'] not in softwares:
softwares[software['name']] = [None] * softwares_length
#update the dictionary value (the list) from None to the software version
softwares[software['name']][count] = software['version']
print(software)
Output
{'openjdk-8-jre': ['8u171-b11-1~deb9u1', '8u171-b11-1~deb9u1', None],
'python2.7': ['2.7.13', None, '2.7.13'],
'npm': ['8.0.0', None, '7.0.0']}