Value Verification in Python Dictionary [duplicate] - python

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

Related

How to set values to a list if it is showing "list index out of range" in python? [duplicate]

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

Find the biggest value in a given list [duplicate]

This question already has answers here:
How to find the maximum number in a list using a loop?
(11 answers)
Closed 2 years ago.
by using only a temporary variable, a for loop, and an if to compare the values-hackinscience.org
Find the biggest value in a given list.
the_list = [
143266561,
1738152473,
312377936,
1027708881,
1495785517,
1858250798,
1693786723,
1871655963,
374455497,
430158267,
]
max_in = 0
for val in the_list:
if val > max_in:
max_in = val
There is the for, there is the if, max_in is somehow a temp var cause it changes over the loop. You get it.
No need for either of that. Use max(the_list).

How to improve a double if statement [duplicate]

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.

Python dict check if certain keys have certain value [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 5 years ago.
beginner question here:
I want to check if certain keys in a dict have a certain value
simplified version of what I tried:
d = {'a':'b', 'b':'b', 'c':'c'}
def b_check():
if d['a'] and d['b'] and d['c'] == 'b':
return True
else:
return False
However, I always get True as the output.
Thanks in advance for the help :)

Conditional key in dictionary - python [duplicate]

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

Categories