Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
The current problem consists of the conversion of a dictionary to a list. I am unable to split the specific value of key and value pair into my desired results.
I have a dictionary that looks like this:
dict = [ {name:aa,age:12, id:121}, {name:bb,age:13, id:122},{name:cc,age:11, id:121}, {name:dd,age:15, id:122} ]
It has certain pairs of key and values and the 'ID' key is the most important of them.the ID value is repeated and so I am looking for lists of that value such that it would looks like this:
121 = [
{name:aa,age:12},
{name:cc,age:11}
]
122 = [
{name:bb,age:13},
{name:dd,age:15}
]
I think this should work fine, just looping through the list of sub-dictionaries.
start_dict = [{'name':'aa','age':12,'id':121}, {'name':'bb','age':13,'id':122},{'name':'cc','age':11,'id':121}, {'name':'dd','age':15,'id':122}]
converted_dict = {}
for subdict in start_dict:
if subdict['id'] not in converted_dict:
converted_dict[subdict['id']] = [{k:v for k,v in subdict.items() if k != 'id'}]
else:
converted_dict[subdict['id']].append({k:v for k,v in subdict.items() if k != 'id'})
print(converted_dict)
{121: [{'name': 'aa', 'age': 12}, {'name': 'cc', 'age': 11}],
122: [{'name': 'bb', 'age': 13}, {'name': 'dd', 'age': 15}]}
from collections import defaultdict
start_dict = [
{'name': 'aa', 'age': 12, 'id': 121},
{'name': 'bb', 'age': 13, 'id': 122},
{'name': 'cc', 'age': 11, 'id': 121},
{'name': 'dd', 'age': 15, 'id': 122},
]
new_dict = defaultdict(list)
for entry in start_dict:
new_dict[entry["id"]].append(dict(name=entry["name"], age=entry["age"]))
print(dict(new_dict))
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
As I understand, a dict has every key unique; if you put two identical key in a dict the first key will be overwritten by the second like this example
my_dict = {
'name': 'John',
'age': 30,
'city': 'New York',
'age': 40
}
print(my_dict)
The result will be
{'name': 'John', 'age': 40, 'city': 'New York'}
How can I manage to do so the second will be overwritten by the first like this example?
my_dict = {
'name': 'John',
'age': 30,
'city': 'New York',
'age': 40
}
print(my_dict)
I want the result to be
{'name': 'John', 'age': 30, 'city': 'New York'}
I tried functions but the dict already does that by default. So no point on doing a function.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I have the following list:
[{'infoType': {'name': 'PERSON_NAME'}, 'count': '71'},
{'infoType': {'name': 'LOCATION'}, 'count': '2'},
]
I would like to transform this list in order to get
[{'name': 'PERSON_NAME',
'count': '71'},
{'name': 'LOCATION',
'count': '2'},
]
Thanks for the help
You can use something like this:
lst = [{'infoType': {'name': 'PERSON_NAME'}, 'count': '71'}, {'infoType': {'name': 'LOCATION'}, 'count': '2'}]
output = []
for d in lst:
newDict = {}
newDict['name'] = d['infoType']['name']
newDict['count'] = d['count']
output.append(newDict)
print(output)
Output:
[{'name': 'PERSON_NAME', 'count': '71'},
{'name': 'LOCATION', 'count': '2'}]
I am using for loop in python and every loop creates a dictionary. I have the below set of dictionaries created.
{'name': 'xxxx'}
{'name': 'yyyy','age':'28'}
{'name': 'zzzz','age':'27','sex':'F'}
My requirement is to compare all the dictionaries created and find out the missing key values and add the key to missing dictionaries and order every dictionary based on key. Below is the expected output
Expected output:
{'age':'','name': 'xxxx','sex':''}
{'age':'28','name': 'yyyy','sex':''}
{'age':'27','name': 'zzzz','sex':'F'}
How to achieve this in python.
If you want to modify the dicts in-place, dict.setdefault would be easy enough.
my_dicts = [
{'name': 'xxxx'},
{'name': 'yyyy','age':'28'},
{'name': 'zzzz','age':'27','sex':'F'},
]
desired_keys = ['name', 'age', 'sex']
for d in my_dicts:
for key in desired_keys:
d.setdefault(key, "")
print(my_dicts)
prints out
[
{'name': 'xxxx', 'age': '', 'sex': ''},
{'name': 'yyyy', 'age': '28', 'sex': ''},
{'name': 'zzzz', 'age': '27', 'sex': 'F'},
]
If you don't want to hard-code the desired_keys list, you can make it a set and gather it from the dicts before the loop above.
desired_keys = set()
for d in my_dicts:
desired_keys.update(set(d)) # update with keys from `d`
Another option, if you want new dicts instead of modifying them in place, is
desired_keys = ... # whichever method you like
empty_dict = dict.fromkeys(desired_keys, "")
new_dicts = [{**empty_dict, **d} for d in my_dicts]
EDIT based on comments:
This doesn't remove keys that are not there in desired keys.
This will leave only the desired keys:
desired_keys = ... # Must be a set
for d in my_dicts:
for key in desired_keys:
d.setdefault(key, "")
for key in set(d) - desired_keys:
d.pop(key)
However, at that point it might be easier to just create new dicts:
new_dicts = [
{key: d.get(value, "") for key in desired_keys}
for d in my_dicts
]
data = [{'name': 'xxxx'},
{'name': 'yyyy','age':'28'},
{'name': 'zzzz','age':'27','sex':'F'}]
First get the maximum, to get all the keys.
Then use dict.get to get default value as empty string for each of the keys, and sort the dictionary on key, you can combine List-comprehension and dict-comprehension:
allKD = max(data, key=len)
[dict(sorted({k:d.get(k, '') for k in allKD}.items(), key=lambda x:x[0])) for d in data]
OUTPUT:
[{'age': '', 'name': 'xxxx', 'sex': ''},
{'age': '28', 'name': 'yyyy', 'sex': ''},
{'age': '27', 'name': 'zzzz', 'sex': 'F'}]
One approach:
from operator import or_
from functools import reduce
lst = [{'name': 'xxxx'},
{'name': 'yyyy', 'age': '28'},
{'name': 'zzzz', 'age': '27', 'sex': 'F'}]
# find all the keys
keys = reduce(or_, map(dict.keys, lst))
# update each dictionary with the complement of the keys
for d in lst:
d.update(dict.fromkeys(keys - d.keys(), ""))
print(lst)
Output
[{'name': 'xxxx', 'age': '', 'sex': ''}, {'name': 'yyyy', 'age': '28', 'sex': ''}, {'name': 'zzzz', 'age': '27', 'sex': 'F'}]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm struggling to get the result from the following code:
list_result = [{'name':'John', 'score':5}, {'name':'John', 'score':6}, {'name':'James', 'score':7}, {'name':'James', 'score':8}]
My expected result is to group them by highest score (to show highest score per user), how do I do that?
Expected Result:
[{'name': 'John', 'score': 6}, {'name': 'James', 'score': 8}]
Here's a way to do it with an ordered dictionary, without pandas:
list_result = [{'name':'John', 'score':5}, {'name':'John', 'score':6}, {'name':'James', 'score':7}, {'name':'James', 'score':8}]
ord_dict = collections.OrderedDict()
for i in sorted(list_result, key=lambda x: x["score"]):
ord_dict[i["name"]] = i["score"]
print([{"name":k, "score":v} for k,v in ord_dict.items()])
The output is:
[{'name': 'John', 'score': 6}, {'name': 'James', 'score': 8}]
You can use pandas.DataFrame and its groupby() method like this:
>>> import pandas as pd
>>> df = pd.DataFrame(list_result)
>>> df.groupby('name').score.max().reset_index().to_dict(orient='records')
[{'name': 'James', 'score': 8}, {'name': 'John', 'score': 6}]
import collections
import math
list_result = [
{'name':'John', 'score': 5},
{'name':'John', 'score': 6},
{'name':'James', 'score': 7},
{'name':'James', 'score': 8}
]
max_score_by_user = collections.defaultdict(lambda: -math.inf)
for result in list_result:
name, score = result['name'], result['score']
max_score_by_user[name] = max(max_score_by_user[name], score)
print(*max_score_by_user.items(), sep='\n')
Which prints:
('John', 6)
('James', 8)
You can try:
list_result = [{'name':'John', 'score':5}, {'name':'John', 'score':6}, {'name':'James', 'score':7}, {'name':'James', 'score':8}]
output_dict = {}
for result in list_result:
if result["name"] in output_dict:
if result["score"] > output_dict[result["name"]]:
output_dict[result["name"]] = result["score"]
else:
output_dict[result["name"]] = result["score"]
output_list = []
for output_key, output_val in output_dict.items():
output_list.append({"name": output_key, "score": output_val})
print(output_list)
Output:
[{'name': 'John', 'score': 6}, {'name': 'James', 'score': 8}]
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])
Copy
Sample Output:
Maximum Value: 5874
Minimum Value: 500
This question already has answers here:
How do I sort a list of dictionaries by a value of the dictionary?
(20 answers)
Closed 8 years ago.
I have list:
[
{'name': 'peter', 'age': 41, 'value': 1},
{'name': 'jon', 'age': 31, 'value': 5},
{'name': 'alan', 'age': 23, 'value': 3}
]
How to sort this list by 'age'?
You can use a lambda function and one of the following functions to sort:
If you want to sort in-place (modify the list):
L.sort(key = lambda d:d['age'])
If you want to create a new sorted list:
print sorted(L, key = lambda d:d['age'])