This question already has answers here:
Only add to a dict if a condition is met
(14 answers)
Closed 4 years ago.
I have a function create_group with an optional parameter user_device=None. If a non-None value is provided for user_device, I want a dictionary targeting_spec to include the key-value pair "user_device": user_device, and if no non-None value is provided, I do not want targeting_spec to include this key-value pair.
How I do it now:
def create_group(..., user_device=None, ...):
...
targeting_spec = {
...
}
if user_device:
targeting_spec["user_device"] = user_device
...
Is this an accepted way of doing this? If not, what is? I ask because this seems like the type of thing Python would love to solve elegantly.
Your approach is fine, provided you don't need to support empty values.
Consider passing in user_device=0, for example. user_device is not None, but it is a falsey value.
If you need to support falsey values apart from None, use is not None to test:
if user_device is not None:
parameters["user_device"] = user_device
Related
This question already has answers here:
Python dictionary - dict.get() return value if dict value is None
(2 answers)
Closed 7 months ago.
When I do a get on a dict that has the value None, it returns a None rather than the default value of the get
d = {"a": None}
d.get("a", {}).get("truc")
Is there any way to do this in one line?
None is still a value and the key exists, so yeah, you won't get the default value. If you need a truthy value, do this:
(d.get('a') or {}).get('truc')
This question already has answers here:
Replace None value in list?
(7 answers)
Closed 1 year ago.
the given list is : List = ['Gopi',10,30,True,'Babu',10.21].
Here I have to replace only the String values to None in python.
Can someone help we with this.
expected o/p - List = ['None',10,30,True,'None',10.21]
Python has the type function that lets you get the type of your variable.
Therefore you can loop on your array and check if the type is String before replacing it by None.
You can just loop through the whole list and check if each item is string with
isinstance(item, str)
This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Closed 2 years ago.
Let's say hypothetically you had a variable called list_a. Sometimes the objects inside are themselves also lists, so multiple indexing might be needed depending on what you want.
You have the following dictionary:
field_dict = {
'name':[1],
'birthdate':[2,5],
'gender':[5,1,3]
}
Each value in the lists above represent how to index list_a to access the needed value.
To get a person's name, I just need to index list_a once, like this: list_a[1].
To access their birthdate, I do list_a[2][5]. This is where the multiple indexing comes in. Likewise, to access gender, I do list_a[5][1][3].
I wonder what the most elegant implementation of this would be - the only solutions I can think of would involve a bit of bruteforcing in the way of hard-coding some details excessively.
As noted in the comments, this does not seem like a great data model. But leaving that aside, I might implement the accessor like:
def get_item(obj, indices):
if indices:
return get_item(obj[indices[0]], indices[1:])
else:
return obj
or iteratively:
def get_item(obj, indices):
while indices:
obj = indices[0]
indices = indices[1:]
return obj
This question already has answers here:
Check if key exists and get the value at the same time in Python?
(3 answers)
Closed 3 years ago.
I would like to optimize this statement:
if 'key' in dictionary and dictionary['key']!=value:
Is there a way to check if a key exists in a dictionary and check the value at the same time?
Use the .get() dict method, which returns None if the key is not in the dictionary instead of throwing a KeyError exception:
d = {'a':0,'b':1}
if d.get('a')==0:
# you will enter this if-statement
if d.get('c')==0:
# you will not enter this if-statement and will not throw a KeyError
Python dict has a get() method. For example, if d is a dict, d.get(x, y) returns d[x] if it exists, otherwise it returns y. This means that your if statement can be replaced with if dictionary.get(key, value) != value.
This question already has answers here:
Find first sequence item that matches a criterion [duplicate]
(2 answers)
Closed 7 years ago.
Is there a built in function in Python that will return a single result given a list and a validation function?
For example I know I can do the following:
resource = list(filter(lambda x: x.uri == uri, subject.resources))[0]
The above will extract a resource from a list of resources, based on ther resource.uri field. Although this field value is uinique, so I know that I will either have 1 or 0 results. filter function will iterate the whole list. In my case its 20 elements, but I want to know if there is some other built-in way to stop the iteration on first match.
See https://docs.python.org/3/library/functions.html#next
next(iterator[, default])
Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
e.g. in your case:
resource = next(filter(lambda x: x.uri == uri, subject.resources), None)