How do i get the biggest value from a dictionary? - python

i still learning python3. please help my problem :)
i have a dictionary
"527740905101197317": {
"lvl": 7,
"exp": 6,
"gems": 333,
"items": {},
"bank": 0
},
"600576767777832972": {
"lvl": 6,
"exp": 14,
"gems": 100,
"items": {},
"bank": 0
},
"580843977352413185": {
"lvl": 1,
"exp": 700,
"gems": 6765,
"items": {},
"bank": 0
},
"720726494640341161": {
"lvl": 3,
"exp": 2,
"gems": 1234,
"items": {},
"bank": 0
},
"657959364933451796": {
"lvl": 1,
"exp": 480,
"gems": 42,
"items": {},
"bank": 0
},
"724932280405065830": {
"lvl": 1,
"exp": 1,
"gems": 1256,
"items": {}
},
how do i get the biggest "gems" with python3?
i've tried some of tutorial, but none of it work.

Iterate over all the dictionaries using the .values() method, select the 'gems' value, and take the maximum.
max(d['gems'] for d in my_data.values())

I'd reccomend using a built-in max function, and specifying a key argument:
max_gems_key = max(dictionary, key=lambda a: dictionary[a]['gems'])
max_gems_val = dictionary[max_gems_key]
Let me simplify and break down everything:
def keyFunction(a):
return dictionary[a]['gems']
max_gems_key = max(dictionary, key=keyFunction)
max_gems_val = dictionary[max_gems_key]
What is happening: I first create a function that finds gems when received the dictionary key - the gems value is what max would use to indentify what's larger, since you can't tell what's larger without it (e.g. is {'a':1,'b':2} > {'a':2,'b':1}?). Then, I call the max function, and it iterates through all the keys, finding the biggest - it, again, uses keyFunc to determine how big a key is, and assignes the biggest key to max_gems_key. A little further information about max usage here.
Hope that's helpful!

As this is a nested dictionary if you want it using pandas you can try this way too.
import pandas as pd
df = pd.DataFrame(data_dict).T
df['gems'].max()

The simplest way if you are a beginner is just to loop over the key,value pairs and keep track of the key for the largest one. Here is a reference to the docs about looping over dictionary items.
You have a nested dictionary, so you are going to loop over the outer dictionary and examine the entries in the inner dictionary to find the largest.
Something like this:
def find_max(my_dict):
key_for_max = None
max_gem = -1
# loop over outer dictionary
for key, value in my_dict.items():
# look into inner dictionary items to find maximum value for the 'gems' key
if value['gems'] > max_gem:
max_gem = value['gems']
key_for_max = key
return key_for_max, max_gem
I am assuming that you want the key for the entry that has the max 'gems' value, not just the value itself.
Other alternatives are to sort it using the 'gems' value as a sorting key, but this is likely the simplest for you to follow as a newer programmer.

Related

First non-null value from a list of dicts

Let's suppose that I want to get the first value of key that is not null inside this list of dicts:
arr = [
{
"key": None,
"anotherkey": 0
},
{
"another": "ignore"
},
{
"bool": True,
"key": "this!"
}
]
Is there some one-liner to do this? I made it using a for loop.
You can loop over the inner dictionaries and check for a key that isn't None using a generator expression within next:
>>> next((d['key'] for d in arr if d.get('key') is not None), None)
'this!'
This will return the first value associated with 'key', otherwise None if no such key/value pairs exist.

Fastest way to get values from dictionary to another dictionary in python without using if?

I need to find a way to get values from one dictionary to another, bases on key name match without using two loops \ if statement.
Main goal is to make it run more efficiently since it's a part of a larger code and run on multiple threads.
If you can keep the dictionary structure it would help
The second dict is initialized with values 0 in advanced
dict_1 = {
"school": {
"main": ["first_key"]
},
"specific": {
"students": [
{
"name": "sam",
"age": 13
},
{
"name": "dan",
"age": 9
},
{
"name": "david",
"age": 20
},
{
"name": "mike",
"age": 5
}
],
"total_students": 4
}
}
dict_2 = {'sam': 0, 'mike': 0, 'david': 0, 'dan': 0, 'total_students': 0}
for i in dict_1["specific"]['students']:
for x in dict_2:
if x == i["name"]:
dict_2[x] = i["age"]
dict_2["total_students"] = dict_1["specific"]["total_students"]
print(dict_2)
Is there more elegant way of doing it?
You don't need two loops at all! You don't even need to initialize dict_2 in advance. Simply loop over dict_1["specific"]["students"] and assign the ages to dict_2 without an if.
for student in dict_1["specific"]["students"]:
student_name = student["name"]
student_age = student["age"]
dict_2[student_name] = student_age
You could also write this as a comprehension:
dict_2 = {student["name"]: student["age"] for student in dict_1["specific"]["students"]}
Both these give the following dict_2:
{'sam': 13, 'dan': 9, 'david': 20, 'mike': 5}
Then you can set dict_2["total_students"] like you already do, but outside any loops.
dict_2["total_students"] = dict_1["specific"]["total_students"]
If you only want to assign ages for students already in dict_2, you need the if. However, you can still do this with a single loop instead of two. :
for student in dict_1["specific"]["students"]:
student_name = student["name"]
if student_name not in dict_2:
continue # skip the rest of this loop
student_age = student["age"]
dict_2[student_name] = student_age
Both these approaches use a single loop, so they're going to be faster than your two-loop approach.
for i in dict_1['specific']['students']:
dict_2[i['name']]=i['age']
dict_2['total_students']=dict_1['specific']['total_students']
Runs in O(N) time and O(N) space.
Yours currently runs in O(N^2) time and O(N) space

Count occurrences of key in nested dictionary with same value then delete if occurrence more than x with python

I currently have a dictionary of dictionaries in Python. They may lo0ok something like this:
stocks = {
"VPER": {
"mentions": 6,
"score": 120,
"currentPrice": 0.0393,
},
"APPL": {
"mentions": 16,
"score": 120,
"currentPrice": 0.0393,
},
"NIO": {
"mentions": 36,
"score": 120,
"currentPrice": 0.0393,
}
}
What I am trying to do is look through the dictionaries and count how many times mentions equals 5, then if that count is 10 remove the nested dictionary (APPL, NIO and so on). So if I had NIO, APPL, TSLA, EPR, EKG, LPD, TTL, AGR, JKR, POP as nested dictionaries and they each had their mentions key set to a value of 5 then I would want to remove them all from the stocks dictionary.
I am not really sure how to go about this, any documentation, advice or examples would be highly appreciated.
CLARIFIED LOGIC:
If there are ten occurrences of mentions: 5 then delete all nested dictionaries where the mentions are equal to five.
counter = sum(value["mentions"] == 5 for key, value in stocks.items())
if counter > 10:
stocks = {key: value for key, value in stocks.items() if value["mentions"] != 5}
You would get the sum of mentions equal to 5 with:
sum(1 for k,v in stocks.items() if v["mentions"]==5)
And you would delete the nested dicts upon that condition with:
stocks={k:v for k,v in stocks.items() if v["mentions"]!=5}

Finding key in a list of dictionaries and sorting the list [duplicate]

This question already has answers here:
How do I sort a list of dictionaries by a value of the dictionary?
(20 answers)
Closed 3 years ago.
Having a JSON-like structure:
{
"shopping_list": [
{
"level": 0,
"position": 0,
"item_name": "Gold Badge"
},
{
"level": 1,
"position": 10,
"item_name": "Silver Badge"
},
{
"level": 2,
"position": 20,
"item_name": "Bronze Badge"
}
]
}
I'm trying to sort the list by key.
However, when trying to get them by:
k = [c.keys()[0] for c in complete_list["shopping_list"]]
I get TypeError: 'dict_keys' object does not support indexing.
How to get keys?
How to sort the list by specified key?
Here it is (admitting the key you mention is 'level'):
k = sorted([c for c in complete_list["shopping_list"]], key=lambda x: x['level'])
print(k)
# >> [{'level': 0, 'position': 0, 'item_name': 'Gold Badge'}, {'level': 1, 'position': 10, 'item_name': 'Silver Badge'}, ...
Try this to get the keys in a list of lists :
d = {
"shopping_list": [
...
}
k = [list(c.keys()) for c in d["shopping_list"]]
print(k)
Output :
[['item_name', 'level', 'position'], ['item_name', 'level', 'position'], ['item_name', 'level', 'position']]
However even if you wanted to sort this list of lists based on some specific key value say value for "level" key or "position" key, the list of lists would remain same.

Dictionary with nested list TypeError: string indices must be integers

My json response come back with this dictionary.
data = {"offset": 0, "per-page": 1, "total": 548, "language": "en",
"odds-type": "DECIMAL", "overall-staked-amount": 23428.63548,
"profit-and-loss": 4439.61471, "events": [{"id": 1042867904480016,
"name": "Gael Monfils vs Daniil Medvedev", "sport-id": 9, "sport-
url": "tennis", "sport-name": "Tennis", "start-time": "2019-02-
16T14:29:00.000Z", "finished-dead-heat": false, "markets": [{"id":
1042867905130015, "name": "Moneyline", "commission": 0, "net-win-
commission": 0, "profit-and-loss": -0.59999, "stake": 0.59999,
"selections": [{"id": "1042867905220015_BACK", "runner-id":
1042867905220015, "name": "Daniil Medvedev", "side": "BACK", "odds":
3.0, "stake": 0.59999, "commission": 0, "profit-and-loss": -0.59999,
"bets": [{"id": 1043769075060320, "offer-id": 1043764555430020,
"matched-time": "2019-02-16T16:16:18.936Z", "settled-time": "2019-
02-16T16:26:01.878Z", "in-play": true, "odds": 3.0, "stake":
0.59999, "commission": 0, "commission-rate": 2.0, "profit-and-loss":
-0.59999, "status": "PAID"}]}], "net-win-commission-rate": 0.02}]}]}
I am unable to get the attribute value for overall-staked-amount and inside the events list I cannot get name from events list. using list comprehension or a for loop.
Here's my code.
list comp
overall_staked = [d['overall-staked-amount'] for d in data]
print(overall_staked)
for loop
for d in data:
overall_staked = d['overall-staked-amount']
name = d['name']
print(overall_staked,name)
I receive an error TypeError: string indices must be integers
what am I doing wrong or need to do?
No need to iterate, just do:
overall_staked = data['overall-staked-amount']
Follow the same logic to get other data
Well, when you iterate over a dictionary, you iterate over its keys, which is a string. And, to access a string you need a int value. That's why you get this error. In your loop, d is a string and you're trying to access it's value with another string instead a int.
Did you get it?
data is a dictionary if you use for instance:
mydict = {"item_1": 3, "item_2": 5}
for item in mydict:
print(item)
it would print the dictionary keys:
item_1
item_2
That are strings, that's why if you try:
mydict = {"item_1": 3, "item_2": 5}
for item in mydict:
# item is a string here, so if you
# Python complains about string indexes must be integers.
item['overall-staked-amount']
it is exactly the same problem for comprehension.
You can get the value you want just by:
overall_staked_amount = data['overall-staked-amount']
You can iterate over keys and items by:
for key, value in data.items():
# ...

Categories

Resources