flattening the list of dictionaries - python-3.x

I have a List of dictionaries that have key and values and other info, like so:
mylist = [ {'key': 'captial' , 'value': 'captial of india'},
{'key': 'captial' , 'value': 'captial of usa'},
{'key': 'fruit' , 'value': 'colour of apple'},
{'key': 'fruit' , 'value': 'colour of orange'}]
How do I flatten the list to get the below output
result=[{'title':'captial',questions:[{text:'captial of usa'},{text:'captial of india'}]},
{'title':'fruit',questions:[{text:'colour of apple'},{text:'colour of orange'}]}]

You can use defaultdict and a list comprehension to achieve your results. defaultdict will group the values of the same keys present in mylist and then you put to use those grouped values with your custom keys(as required in your result) using a list comprehension.
from collections import defaultdict
mylist = [...]
a_list = defaultdict(list)
for item in mylist:
a_list[item["key"]].append(item["value"])
result = [
{"title": key, "questions": [{"text": v} for v in value]}
for key, value in a_list.items()
]
Output:
[
{
"title": "captial",
"questions": [{"text": "captial of india"}, {"text": "captial of usa"}],
},
{
"title": "fruit",
"questions": [{"text": "colour of apple"}, {"text": "colour of orange"}],
},
]

Related

How to remove common item from list of dictionaries after grouping

I have a list of dictionaries like below. I want to group the dictionaries based on grade, and convert the list of dictionaries to single dictionaries with key as grade value and value as list of dictionaries
Input:
[
{'name':'abc','mark':'99','grade':'A'},
{'name':'xyz','mark':'90','grade':'A'},
{'name':'123','mark':'70','grade':'C'},
]
I want my output like below:
{
A: [ {'name': 'abc','mark':'99'}, {'name': 'xyz','mark':'90'} ],
C: [ {'name': '123','mark':'70'} ]
}
I tried sorted and groupby; but not able to remove grade from dictionary.
Use a loop with dict.setdefault:
l = [{'name':'abc','mark':'99','grade':'A'},
{'name':'xyz','mark':'90','grade':'A'},
{'name':'123','mark':'70','grade':'C'},
]
out = {}
for d in l:
# avoid mutating the original dictionaries
d = d.copy()
# get grade, try to get the key in "out"
# if the key doesn't exist, initialize with an empty list
out.setdefault(d.pop('grade'), []).append(d)
print(out)
Output:
{'A': [{'name': 'abc', 'mark': '99'},
{'name': 'xyz', 'mark': '90'}],
'C': [{'name': '123', 'mark': '70'}],
}

adding values to objects in dictionary

I want to add the following to each object in a dictionary.
My dictionary looks like this:
{'Niveau1Obj1': {'Niveau2Obj1': {'Niveau3Obj1': {}}}}
For each object I want to add the following value:
{'type':'object'}
So the final outcome should look something like this:
{'Niveau1Obj1': {'type': 'object'}, 'Niveau2Obj1': {'type': 'object'}, 'Niveau3Obj1': {'type': 'object'}}
My code doesn't result in the desired outcome. The code is:
objects = {'Niveau1Obj1': {'Niveau2Obj1': {'Niveau3Obj1': {}}}}
for key, obj in objects.items():
objects[key].setdefault(key, {}).update({'type':'object'})
It only adds the {'type':'object'} only to the last part of the dictionary.
What am I doing wrong?
Try a recursion:
dct = {"Niveau1Obj1": {"Niveau2Obj1": {"Niveau3Obj1": {}}}}
def get_keys(d):
if isinstance(d, dict):
for k in d:
yield k
yield from get_keys(d[k])
out = {k: {"type": "object"} for k in get_keys(dct)}
print(out)
Prints:
{
"Niveau1Obj1": {"type": "object"},
"Niveau2Obj1": {"type": "object"},
"Niveau3Obj1": {"type": "object"},
}

Getting error when doing re-mapping dict keys to another dict keys in python

below is my code:
mapping_dict = {"NET_D":
[
("name", "tiN"),
("d_id", "id"),
("m_ip", "ti_ip"),
("model", "cmbM"),
("dc", "cmbL"),
("vendor", "cmbV"),
("cab", "cmbC")
]
}
obj = {"ti_ip": "1.1.1.1", "cmbM": "model-a", "tiN": "device-123", "cmbV": "Systems", "cmbCt": "406", "cmbC": "sc", "id": "199"}
def process_results(item_list, mapping):
results = []
for i in item_list:
item = {}
for m in mapping:
try:
item[m[0]] = i[m[1]]
except KeyError:
item[m[0]] = ""
results.append(item)
return results, len(results)
process_results(obj, mapping_dict["NET_D"])
desired/wanted output:
{"m_ip": "1.1.1.1", "model": "model-a", "name": "device-123", "vendor": "Systems", "cab": "406", "dc": "sc", "d_id": "199"}
error i am getting:
process_results
item[m[0]] = i[m[1]]
TypeError: string indices must be integers
can anyone suggest the right way to achieve desired/wanted output
i am still new to python, apologies for the mistakes/errors or if my code sounds like silly/dumb ;-) to you
You could do this, although technically your mapping_dict is a list of tuples and not a nested dict.
mapping_dict = {"NET_D":
[
("name", "tiN"),
("d_id", "id"),
("m_ip", "ti_ip"),
("model", "cmbM"),
("dc", "cmbL"),
("vendor", "cmbV"),
("cab", "cmbC")
]
}
obj = {"ti_ip": "1.1.1.1", "cmbM": "model-a", "tiN": "device-123", "cmbV": "Systems", "cmbCt": "406", "cmbC": "sc", "id": "199"}
def process_results(item_list, mapping):
return {i[0]:v for k,v in item_list.items() for i in mapping if k == i[1]}
which will give
{'m_ip': '1.1.1.1', 'model': 'model-a', 'name': 'device-123', 'vendor': 'Systems', 'cab': 'sc', 'd_id': '199'}```
This is called dict comprehension and creates a new dictionary.
It is basically doing the equivalent of
def process_results(item_list, mapping):
res = {}
for k,v in item_list.items():
for i in mapping:
if k == i[1]:
res[i[0]] = v
return res
Iterating for each value of the obj dict, then iterate through the mapping list of tuples and if the value is the same as index[1] of the tuple then create a new key:value in the new dict.

How to get the value of the first key of each dictionary in a list using LOOP?

Sample code:
dict1 = {"firstname":"Anna", "lastname":"Lupe", "ID":12000789}
dict2 = {"firstname":"Max", "lastname":"Mustermann", "ID":12345}
list_of_dict = [dict1, dict2]
print(list_of_dict)
Output:
[{'firstname': 'Anna', 'lastname': 'Lupe', 'ID': 12000789}, {'firstname': 'Max', 'lastname': 'Mustermann', 'ID': 12345}]
How can I get(print) all first names using a LOOP? Say, something like:
for el in list_of_dict:
print el[0]
However dictionary does not support indexing...
Get dict keys using dict.keys(), then convert it to a list and get first one.
dict1 = {"firstname": "Anna", "lastname": "Lupe", "ID": 12000789}
dict2 = {"firstname": "Max", "lastname": "Mustermann", "ID": 12345}
list_of_dict = [dict1, dict2]
print(list_of_dict)
for el in list_of_dict:
first_key = list(el.keys())[0]
print(el[first_key])

Maximum Value From List with Dictionary

I'm trying to get the dictionary with the biggest value in the key
'points'.
So, I have the following list and I'm trying to create a function where the output will be the item from the list (in this case a dictionary) with the biggest value in the key points).
[ {"name":"John","points":4} , {"name": "Michael", "points":10} ]
I want the output to be:
{"name": "Michael", "points":10}
I 'm not posting any code because I have no idea of how to do this.
Thank you for the help!
Try the following:
max(scores, key=lambda item: item['points'])
>>> scores = [ {"name":"John","points":4} , {"name": "Michael", "points":10} ]
>>> max(scores, key=lambda item: item['points'])
{'points': 10, 'name': 'Michael'}
>>>

Resources