Reputation: 6920
I have a list of dictionaries, in which I'm trying to make the value of key 'Username' as the key in a new dictionary, and subsequent key-value pairs as a dictionary value to the 'Username' key in the new dictionary.
One of the checks involves returning the first element from the list if the GECOS
value is a list, otherwise return the string value of the GECOS
key.
For the first two dictionaries, I'm not able to get the entire string.
I have the data below:
test_list = [
{
"Username": "root",
"UID": "0",
"GECOS": "root",
"Group List": [
""
]
},
{
"Username": "daemon",
"UID": "1",
"GECOS": "daemon",
"Group List": [
""
]
},
{
"Username": "hplip",
"UID": "118",
"GECOS": [
"HPLIP system user",
"",
"",
""
],
"Group List": [
""
]
},
{
"Username": "speech-dispatcher",
"UID": "111",
"GECOS": [
"Speech Dispatcher",
"",
"",
""
],
"Group List": [
"pulse",
"test"
]
}
]
and the following code:
import json
new_dict = {}
for dict_item in test_list:
for key in dict_item:
new_dict[dict_item["Username"]] = {
'UID'.title().lower(): dict_item['UID'],
'GECOS'.title(): dict_item['GECOS'][0] if isinstance(dict_item[key], list) else dict_item['GECOS'],
'Group List'.title(): [] if all('' == s or s.isspace() for s in dict_item['Group List']) else dict_item['Group List']
}
print(json.dumps(new_dict, indent=4))
The output of this is:
{
"root": {
"uid": "0",
"Gecos": "r",
"Group List": []
},
"daemon": {
"uid": "1",
"Gecos": "d",
"Group List": []
},
"hplip": {
"uid": "118",
"Gecos": "HPLIP system user",
"Group List": []
},
"speech-dispatcher": {
"uid": "111",
"Gecos": "Speech Dispatcher",
"Group List": [
"pulse",
"test"
]
}
}
And the expected output is:
{
"root": {
"uid": "0",
"Gecos": "root",
"Group List": []
},
"daemon": {
"uid": "1",
"Gecos": "daemon",
"Group List": []
},
"hplip": {
"uid": "118",
"Gecos": "HPLIP system user",
"Group List": []
},
"speech-dispatcher": {
"uid": "111",
"Gecos": "Speech Dispatcher",
"Group List": [
"pulse",
"test"
]
}
}
Upvotes: 4
Views: 505
Reputation: 106465
You should not iterate through the keys of each dict. Instead, access the keys directly, as a dict should:
import json
new_dict = {}
for dict_item in test_list:
new_dict[dict_item["Username"]] = {
'UID'.title().lower(): dict_item['UID'],
'GECOS'.title(): dict_item['GECOS'][0] if isinstance(dict_item['GECOS'], list) else dict_item['GECOS'],
'Group List'.title(): [] if all('' == s or s.isspace() for s in dict_item['Group List']) else dict_item['Group List']
}
print(json.dumps(new_dict, indent=4))
Upvotes: 3