I have list of dictionaries and I am trying to take each dictionary and group them into one dictionary after iterations. Is there a simple way of doing this. So far I am taking each dictionary after each iteration and appending them into a list. After the iteration I get an output like below:
data = [{'disabled': False, 'id': '28394', 'self': 'www.google.com/28394', 'value': 'Tuesday'}, {'disabled': False, 'id': '23433', 'self': 'www.google.com/23433', 'value': 'Wednsday'}]
I would like to either convert it from a list to a single dictionary or somehow merge each dictionary into one like below.
data = {'disabled': False, 'id': '28394', 'self': 'www.google.com/28394', 'value': 'Tuesday', 'disabled': False, 'id': '23433', 'self': 'www.google.com/23433', 'value': 'Wednsday'}
Once I get that I want to add the dictionary using the dict() method that creates the empty dictionary to store those values.
Below is my code:
elif(key == 'customfield_12951'):
newDictionaryValues = []
for issueItemInspection in oIssues['customfield']:
if(oIssues[key] == None):
values = {'value': None}
verificationDictNone = dict(values)
iterateDictIssues(verificationDictNone, listInner)
else:
if(len(oIssues[key]) == 1):
values = issueItemInspection
verificationDict = dict(values)
iterateDictIssues(verificationDict, listInner)
else:
values = issueItemInspection
newDictionaryValues.append(values)
print(newDictionaryValues)
verificationDictValues = dict(values)
iterateDictIssues(verificationDictValues, listInner)
There are multiple keys holding each dictionary and as you can see the issueItemInspection is carrying each individual dictionary. As each key dictionary gets appended I would like to merge these all into one or convert it from a list to a single dictionary. Right now it is a big list of dictionaries.
CodePudding user response:
I don't fully understand your point, but how about storing values with same keys into list?
from collections import defaultdict
data = [{'disabled': False, 'id': '28394', 'self': 'www.google.com/28394', 'value': 'Tuesday'}, {'disabled': False, 'id': '23433', 'self': 'www.google.com/23433', 'value': 'Wednsday'}]
d = defaultdict(list)
for dictionary in data:
for k, v in dictionary.items():
d[k].append(v)
print(d)
CodePudding user response:
You can't get to the requested data since your dictionnary have multiple key definition, it will only keep the last key value:
>>> dict_test = {'test': 1, 'test': 2}
>>> print(dict_test )
{'test': 2}