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.
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:
Why doesn't list have safe "get" method like dictionary?
(13 answers)
Closed 1 year ago.
In python we have get() method in dictionary to get values safely. Any way to achieve this in list?
my_dict = {'fruit':'apple','colour':'black'}
my_dict.get('colour','None') #returns black
my_dict.get('veg','None') #returns None
my_list = ['apple','fish','blue','bottle','gold']
colour = my_list[2]
print(colour) #returns blue
value = my_list[7] #gives error. Expected: need to return default value as None.
In my case length of my_list is not constant.Values are getting populated in runtime.If i try to get the index which is not present in the my_list it should return default value as None.
How to get the default values when list is not having requested index.?
Use try-except block -
try:
value = my_list[7]
except:
print("Value doesn't exist")
In case, the try statement has an error, it switches to the except block
This question already has answers here:
Check if a given key already exists in a dictionary
(16 answers)
Closed 3 years ago.
Please advise what is the correct way to verify if key x is stored in a dictionary dict. and if it is, set a value check to True and otherwise it will be set to False.
check = True
try :
y = d.x
except KeyError as e
check = False
Or is it the right way to do one the following?
check = dict.contains(x)
check = dict.has_key(x)
check = x in dict
check = x.is_elem(dict)
The most common approach seems to be x in d
This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 5 years ago.
I am having issues with values being returned exactly as they are passed to a method despite being modified inside the method.
def test(value):
value+=1
return value
value = 0
while True:
test(value)
print(value)
This stripped-down example simply returns zero every time instead of increasing integers as one might expect. Why is this, and how can I fix it?
I am not asking how the return statement works/what is does, just why my value isn't updating.
You need to assign the return'd value back
value = test(value)
Use this :-
def test(value):
value+=1
return value
value = 0
while True:
print(test(value))
You weren't using the returned value and using the test(value) inside the print statement saves you from creating another variable.
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