You can use dict.get()
value = d.get(key)
which will return None if key is not in d. You can also provide a different default value that will be returned instead of None (unless the dict actually contains None as the value for this key):
value = d.get(key, "empty")
Answer from Tim Pietzcker on Stack OverflowYou can use dict.get()
value = d.get(key)
which will return None if key is not in d. You can also provide a different default value that will be returned instead of None (unless the dict actually contains None as the value for this key):
value = d.get(key, "empty")
Wonder no more. It's built into the language.
>>> help(dict)
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
...
|
| get(...)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
...
Good day,
is there a way to get dictionary value or default if key doesn't exist OR value is None?
e.g.
x = { 'a': 1, 'c': None }
x.get('b', 2) # I want b = 2, I have it
x.get('c', 3) # I want c = 3, but key 'c' exists, so I get c = NoneI can of course create own dict object and override "get" or implement additional method, but maybe there's a fancy standard way?
p.s. simple practical example "for what":
You need to parse YAML file, there's array key "items":
items: - 1 - 2 - 3
If key is empty, any YAML parser set it to "None", however it's much better to have an empty list instead.
for message in d.get('messages') or ():
do_something()
getreturnsNoneby default for missing keys.a or bevaluates tobwhenbool(a) == False. An empty list andNoneare examples of values that are false in a boolean context.- Note that you cannot use this trick if you intend to modify the possibly empty list that is already in the dict. I'm using
()instead of[]to guard against such mistakes. Also, CPython caches the empty tuple, so using it is slightly faster than constructing an empty list.
You have to check for the existence of 'messages' AND the content of 'messages'. It's the same thing you have, but I would write it as:
if 'messages' in d and d['messages'] is not None:
for m in d['messages']:
do_something(m)
You can use the setdefault method
my_dict = {"a":1,"b":2}
If a key exists, there is no change made to the existing value
my_dict.setdefault('a', 3)
print(my_dict) #{'a': 1, 'b': 2}
If it doesn't exist, the key-value pair is added
my_dict.setdefault('c', 3)
print(my_dict) #{'a': 1, 'b': 2, 'c': 3}
Looping through multiple keys :
my_dict = {"a":1,"b":2}
keys = ["a","c","d"]
for key in keys:
my_dict.setdefault(key, "Not Available")
print(my_dict) #{'a': 1, 'b': 2, 'c': 'Not Available', 'd': 'Not Available'}
You could use dict.get(key[, default]):
>>> d = {'key1': 'apple'}
>>> d['key1']
'apple'
>>> d.get('key2', 'Not Available')
'Not Available'
Use a try / except clause to catch KeyError:
for item in parseddoc["findItemsByKeywordsResponse"][0]["searchResult"][0]["item"]:
try:
condition = item['condition'][0]['conditionDisplayName'][0]
except KeyError:
condition = 'N/A'
print(condition)
Add the following if/else statement to your loop:
for item in (parseddoc["findItemsByKeywordsResponse"][0]["searchResult"][0]["item"]):
if 'condition' not in item:
condition = 'N/A'
else:
condition = item['condition'][0]['conditionDisplayName'][0]
print(condition)
Hi all,
The code snippet I need help with uses the Spotify API to find artists that use certain genres as tags. The variable "results" is a dictionary of dictionaries of three artists who use said genre (I don't know why it's not returned as a json, but I'm not mad). In this dictionary there is a lot of information I don't need, so the function picks out the information I need and makes new, smaller dictionaries that it then appends to a list to be used later on in the program. So far, so good. However, I don't want the program to crash if certain information doesn't exist for an artist down the line. Say if they don't have an image, or whatever.
So, I was wondering if there was a way to have it default to a certain value if a key doesn't exist in the results dictionary. If a key does exist and the value is None, that's fine. The suggested thing is to use defaultdict, which honestly makes my brain fall flat. Would it be 'pythonic' to first make a dictionary on every iteration of the loop with all the values set to None, and then override them if they do exist? I feel like I could make that work, but it feels inelegant.
Here is the function in question:
def find_artists(targets: list = None) -> list:
"""
:param targets: Takes a list of genres to be searched for
:return: Returns a list of dictionaries that contain
the genre, artist_name, follower_count, artist_image, and the url
"""
artists = []
for genre in targets:
results = spotify.search(q=f'genre:{genre}', type='artist', limit=3)
for entry in results["artists"]["items"]:
temp_dict = {
'genre': genre,
'artist_name': entry['name'],
'follower_count': entry['followers']['total'],
'artist_image': entry['images'][0]['url'],
'url': entry['external_urls']['spotify']
}
artists.append(temp_dict)
return artistsI took a long break from coding, and am just now getting back into it, so I'm rusty as heck. Excuse any obvious errors, but please point them out! Also, let me know if you don't think this would be an issue, I'm not very versed in APIs.
Thanks in advance for your time.
EDIT: Typos and fixed the code block