check if the value in a dict is not empty? - python

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)

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)

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.

Python Creating new dict from specific keys in other dict (nested)

(Please note I searched and couldn't find an answer for this type of nested, with dict and lists, and with keeping keys names and values).
I'm trying to create a new dict from existing dict with specific keys-value pairs that I need.
Example/origin dict:
{
"test1":{
"test2":[
]
},
"test3":[
],
"test4":{
"test5":0,
"what":{
"in":"2",
"out":"4"
}
},
"test12":[
{
"in2":"a",
"out2":"b"
},
{
"in2":"a33",
"out2":"b33"
}
],
"test9":255
}
I want to select keys for example: ['test1'], ['test4'], ['test12']['in2']
in such way that the result dict will be:
{
"test1":{
"test2":[
]
},
"test4":{
"test5":0,
"what":{
"in":"2",
"out":"4"
}
},
"test12":[
{
"in2":"a"
},
{
"in2":"a33"
}
]
}
I'm aware its possible to do manually, i want to see the pythonic way :)
Thanks!!!
Try a dictionary comprehension with isinstance list:
>>> {k: ([{'in2': i['in2']} for i in v] if isinstance(v, list) else v) for k, v in dct.items() if not isinstance(v, int) and v}
{'test1': {'test2': []},
'test4': {'test5': 0, 'what': {'in': '2', 'out': '4'}},
'test12': [{'in2': 'a'}, {'in2': 'a33'}]}
>>>
I don't think there is one "pythonic" way to do what you want here as there is an infinite number of possible values for your nested dict.
Here is a start of answer that you can adapt to your need !
import copy
def _transform(source_dict: dict, keys_to_keep: list):
dict_copy = copy.deepcopy(source_dict) # no side-effects
for key, value in source_dict.items():
if key not in keys_to_keep:
dict_copy.pop(key)
elif isinstance(value, dict):
dict_copy[key] = _transform(value, keys_to_keep)
elif isinstance(value, list):
dict_copy[key] = [
_transform(el, keys_to_keep) if isinstance(el, dict) else el for el in value
]
return dict_copy

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'])

Categories

Resources