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'}]
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.
Fairly new to list comprehension and have the_list that I want to extract the keys of nested dictionary but I got the values instead. What am I missing or what am I doing wrong?
the_list = [{'size': 0, 'values': [], 'start': 0}, {'size': 2, 'values': [{'user': {'name': 'anna', 'id': 10, 'displayName': 'Anna'}, 'category': 'Secretary'}, {'user': {'name': 'bob', 'id': 11, 'displayName': 'Bobby'}, 'category': 'Manager'}], 'start': 0}, {'size': 1, 'values': [{'user': {'name': 'claire', 'id': 13, 'displayName': 'Clarissa Claire'}, 'category': 'Secretary'}], 'start': 0}]
list_comprehension = []
list_comprehension = [x for x in the_list for x in the_list[1]['values'][0]]
print(list_comprehension)
>> ['user', 'category', 'user', 'category', 'user', 'category']
Want
list_comprehension = [[anna, Secretary], [bob, manager], [claire, Secretary]]
You could use this. I personnally try to avoid nested list comprehension as they are hard to read and debug.
[[x['category'], x['user']['displayName']] for nest_list in the_list for x in nest_list["values"] ]
Output:
[['Secretary', 'Anna'], ['Manager', 'Bobby'], ['Secretary', 'Clarissa Claire']]
EDIT:
A version that doesn't have a nested comprehension list. When doing it I realised that there was one more level than I realised that makes this version a bit long. So in the end I'm not sure which one I would use in prod.
result = []
dict_list = [nest_list["values"] for nest_list in the_list]
for elt in dict_list:
for d in elt:
result.append([d['category'], d['user']['displayName']])
I've come up with this solution, but it is not very readable ...
comprehensionList = [[user['user']['name'], user['category']] for x in the_list for user in x['values']]
# Output
[['anna', 'Secretary'], ['bob', 'Manager'], ['claire', 'Secretary']]
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))
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
I want to insert something in Python 3.8 with Pymongo
I got a short question. I have a list of dictionaries called items:
item_list = [{'name': 'abc', 'category': 'cde', 'assurance': 0.9844486508518457, 'count': 1},
{'name': 'abc', 'category': 'cde', 'assurance': 0.7428154349327087, 'count': 1},
{'name': 'abc', 'category': 'cde', 'assurance': 0.9954652488231659, 'count': 1}]
I also have my database item:
item = collection.find_one(<placeholder>)
Now I tried the following:
collection.update_one(item, {"$set": {"Entity": item_list} }, True)
But this does not work... How can I insert a list of dictionaries?
Thank you.