First non-null value from a list of dicts - python

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.

Related

python replace json list values without knowing the keys

I have this code snippet:
data = {
"links": [
{"key_name_not_known": "replace_by_first_value_in_list"},
{"key_name_not_known": "replace_by_second_value_in_list"},
]
}
list = ["hello1", "hello2"]
Here I want to replace both values "hello" in data["links"] ["keys"]? without knowing the key value by the two values in the list, in the right order.
A goal output would be:
data = {
"links": [
{"key_name_not_known": "hello1"},
{"key_name_not_known": "hello2"},
]
}
How can I do that ?
for index, obj in enumerate(data['links']):
for key,val in obj.items():
if len(list) > index:
data['links'][index][key] = list[index]

Python3 - loop through list with mulitple dictionaries

sorry I am rather a beginner when it comes to python.
I have a list like this:
"list": [
{
"id": 12345,
"name": "test"
},
{
"id": 12453,
"value": "value1",
"field": "test",
}
]
When looping through several of such lists I want it to print the "name" key from the upper dictionary but only if the condition is met that "value": "value1", is present but this is in a different dictionary.
I tried with stuff like: if 'value' in event.keys():
but I cant manage to only print this "name" key if the other condition is met. any suggestions?
Below one way of doing it, it is going through all key/value of all dictionnaries so it's probably not efficient but will adapt to several possibility.
I don't know if name can be in the list several times, the below code will keep the last occurrence if it happens.
I made it a function so that you can use it easily on several similar lists. It returns None if the criteria was not met, the value of name if it was.
def get_valid_name(dict_list, target_value):
keep_name = False
current_name = None
for d in dict_list:
for key, val in d.items():
if key == "name":
current_name = val
elif key == "value" and val == target_value:
keep_name = True
return current_name if keep_name else None
for l in [original_list]:
result = get_valid_name(l, "value1")
if result is not None:
print(result)

How do i get the biggest value from a dictionary?

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.

Remove duplicate of a dictionary from list

How can i remove duplicate of the key "name"
[
{
'items':[
{
'$oid':'5a192d0590866ecc5c1f1683'
}
],
'image':'image12',
'_id':{
'$oid':'5a106f7490866e25ddf70cef'
},
'name':'Amala',
'store':{
'$oid':'5a0a10ad90866e5abae59470'
}
},
{
'items':[
{
'$oid':'5a192d2890866ecc5c1f1684'
}
],
'image':'fourth shit',
'_id':{
'$oid':'5a106fa190866e25ddf70cf0'
},
'name':'Amala',
'store':{
'$oid':'5a0a10ad90866e5abae59470'
}
}
]
I want to marge together dictionary with the same key "name"
Here is what i have tried
b = []
for q in data:
if len(data) == 0:
b.append(q)
else:
for y in b:
if q['name'] != y['name']:
b.append(q)
but after trying this the b list doesn't return unique dictionary that i wanted
You loop through the assembled list and if you find a dict with a different name, you add the current dict. The logic should be different: only add it if you don't find one with the same name!
That being said, you should maintain a set of seen names. That will make the check more performant:
b, seen = [], set()
for q in data:
if q['name'] not in seen:
b.append(q)
seen.add(q['name'])

check if the value in a dict is not empty?

I have a dict theaterinfo like this :
"Showtimes":{
"New York": [
{
"Times": {},
"theaterid": 61,
}
]
"Ohio": [
{
"Times": {'2015-01-10',
'2015-01-11'},
"theaterid": 1,
}
]
}
How can I deal with that if Times in empty,don't print it out??
An empty dictionary evaluates to a boolean False while a non-empty dict evaluates to True, so you can write
if my_dict['Times']:
print(my_dict['Times'])
You need to iterate over the dict["Showtimes"] items then access the dict in the list using the Times key and check using an if which will return False for an empty dict.
d = {"Showtimes":{
"New York": [
{
"Times": {},
"theaterid": 61,
}
],
"Ohio": [
{
"Times": {'2015-01-10',
'2015-01-11'},
"theaterid": 1,
}
]
}}
for k,v in d["Showtimes"].iteritems():
if v[0]["Times"]:
print(k,v)
('Ohio', [{'theaterid': 1, 'Times': set(['2015-01-10', '2015-01-11'])}])
One thing to be careful of is if you have a value like 0, this will also return False so if you only want to check if the value is an empty dict use if v[0]["Times"] != {}
If you want to check all values of Times and only print the full dict if there are no empty Times values you can use all which will short circuit on the first occurrence of an empty value:
if all(v[0]["Times"] for v in d["Showtimes"].itervalues()):
print(d)
Or reverse the logic with any:
if not any(not v[0]["Times"] for v in d["Showtimes"].itervalues()):
print(d)
If there is a chance a dict won't have a Times key use v[0].get("Times",1)

Categories

Resources