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'}
>>>
Related
i have an array of JSON objects that arrived from the source I can't control, and sometimes there are values, like this:
[{"name": "HDD", "brand": "Samsung", "price": "$100"},
<NULL>,
{"name": "Mouse", "brand": "Logitech", "price": "$10"}]
is there any way to handle it in python? I'm getting a syntax error on reading the value.
i tried to put it this way:
try:
products = sorted(products, key=lambda k: k['price'], reverse=True)
except SyntaxError:
print("Error")
but no luck.
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'}],
}
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"}],
},
]
Been looking through Stackoverflow and documentations for 2 days now, I am a beginner, and I just can't progress. I am using Python 3.8.
I have a list of dictionaries:
books = [{'Type': 'Book', 'Date': '2011', 'Publication Year': '2011', 'Place Published': 'New York', 'Publisher': 'Simon & Schuster', 'Author': 'Walter Isaacson', 'ISBN': '978-1-4516-4853-9', 'Title': 'Test Steve Jobs'}, {'Type': 'Book', 'Date': '2001', 'Publication Year': '2001', 'Place Published': 'Oxford', 'Publisher': 'Oxford University press', 'Author': 'Peter Hall', 'ISBN': '978-0-19-924775-2', 'Title': 'Test Varieties of capitalism: the institutional foundations of comparative advantage'}]
print(books)
I want to make the key "Type" into a lowercase "type".
But with the following List Comprehension it somehow makes the key to a value and vice versa.
lower_list = [ { v:k.lower() for k,v in d.items() } for d in books ]
print(lower_list)
I end up with [{'Book': 'type',.... when it should be [{'type': 'Book',....
I am struggling with understanding the list comprehension syntax still, so would be grateful for 1. somebody explaining what my list comprehension does in plain English and 2. how to change it to achieve what I am looking for. :)
Thank you!
So your first problem:
lower_list = [ { k.lower():v for k,v in d.items() } for d in books ] ?
You was inverting key and values.
Your last question how to skip lowercasing the ISBN key:
[ { k if k is "ISBN" else k.lower():v.lower() for k,v in d.items()} for d in books ]
But you should consider using a for loop: if your need more operations or conditions, it would start to be difficult to modify further.
my_final_books = []
for d in books:
for k,v in d.items():
if k is "ISBN":
key = k
else:
key = k.lower()
# or ternary form key = k if k is "ISBN" else k.lower()
my_final_books.append({key:v})
# do more logic here
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])