Is it possible to check none value in dict
dict = {'a':'None','b':'12345','c':'None'}
My code
for k,v in d.items():
if d[k] != None:
print "good"
else:
print "Bad
Prints three good after executing above code snippet.
good
good
good
Required:If value is None than not printing good for dict key a and c.
Your none values are actually strings in your dictionary.
You can check for 'None'
or use actual python None value.
d = {'a':None,'b':'12345','c':None}
for k,v in d.items():
if d[k] is None:
print "good"
else:
print "Bad"
prints "good" 2 times
Or if you Have to use your current dictionary just change your check to look for 'None'
additionally dict is a python built in type so it is a good idea not to name variables dict
Define your dictionary with
d = {'a': None}
rather than
d = {'a': 'None'}
In the latter case, 'None' is just a string, not Python's None type. Also, test for None with the identity operator is:
for key, value in d.iteritems():
if value is None:
print "None found!"
def none_in_dict(d):
for _, value in d.items():
if value is None:
return True
return False
And the use is:
if none_in_dict(my_dict):
logger.error(my_err_msg)
Instead of using "if value is None" you can simply use
d = {'a':None, 'b':'12345', 'c':None, 'd':'None'}
for k, v in d.items():
if v:
print("good")
else:
print("bad")
"if v" will be True if there is any kind of value except None. Hence you don't have to explicitly use None keyword in if condition (if v is None).
Result:
bad
good
bad
good
In last case the value for key 'd' is 'None' - as a string not python value None
Related
Here is a piece of code where the length of v is either 0, 1 or 2, and can contain identical or different data and data types.
result = False
v = [3, 4] # just an example, could be v = [None, None] instead
try:
result |= v[0] == v[1] is not None # THIS IS THE TEST
except Exception:
pass
How should the line result |= v[0] == v[1] is not None be understood? Should it be written in another way (whatever it is supposed to be doing)?
First, to know what this test is doing, you need to know what |= means.
|=, is the same sort of shortcut as +=, this means that
a |= b
actually means
a = a | b
A common case for the operator | is for dictionnaries :
dict1 = {"a":10, "b":12}
dict2 = {"c":80, "d":37}
dict3 = dict1 | dict2
print(dict3)
Result :
{"a":10, "b":12, "c":80, "d":37}
This is a sort of "merge" operator, it merges an union with another union, or data with another data, to be simple.
Now that this is understood, we need to focus on the other part of the test :
v[0] == v[1] is not None
This test simply means
Does the condition v[0] == v[1] equals not None?
If it does equals to not None, returns True
In this case: v[0] = 3 and v[1] = 4
So, this condition is :
(3 == 4) is (not None)
False is (not None)
False isn't not None
So, this test returns False.
Now, the full test : result |= v[0] == v[1] is not None
What does it do ? It symply do :
Merge the variable result equals to the returned value of the test v[0] == v[1] is not None
As we know, this : v[0] == v[1] is not None returns False, so it simply says :
Merge the variable result with the returned value of v[0] == v[1] is not None
So :
Merge the variable result with False
False merged with False makes False. So,all of this simply makes the result variable being False.
This is why, when printing result, it prints False !
(Hope that helps)
I need help creating a function that goes through a given dictionary. The value associated with that key may be another key to the dictionary. i need the function to keep looking up the keys until it reaches a key that has no associated value.
def follow_me(d, s):
while d:
if s in d:
return d[s]
I can return the value in the dictionary that s equals to but I've no idea how to iterate through it until I get a value that has no associated value. So I can get the value that badger is doe, but how do I iterate through the dictionary until I get fox and then fox to hen etc.
d = {'badger':'doe', 'doe':'fox', 'fox':'hen','hen':'flea',
'sparrow':'spider', 'zebra':'lion', 'lion':'zebra'}
print(follow_me(d, 'badger'))
print(follow_me(d, 'fox'))
print(follow_me(d, 'sparrow'))
print(follow_me(d, 'zebra'))
print(follow_me(d, 'aardvark'))
and this is what I currently have of the function that makes sense to me because everything else I've tried is just wrong.
def follow_me(d, s):
while d:
if s in d:
return d[s]
and the output needs to be:
flea
flea
spider
aardvark
but my code right now is producing:
doe
hen
spider
lion
To extend on the other answers, which are still valid. If you have a very large dictionary then using key not in dic.keys() or k in d iterates through all keys every loop.
To go around this, one can use a try catch:
def follow_me(dic, key):
while True:
if key not in dic.keys():
return key
key = dic[key]
def follow_me2(dic, key):
try:
while True:
key = dic[key]
except Exception as e:
return key
import time
d = { i: (i+1) for i in range(10000000) }
start = time.time()
follow_me(d, 0)
print("Using 'in' takes", time.time() - start,"s")
start = time.time()
follow_me2(d, 0)
print("Using 'try' takes", time.time() - start,"s")
gives the output:
Using 'in' takes 2.476428747177124 s
Using 'try' takes 0.9100546836853027 s
I think this is what you are looking for, though your problem description is very unclear:
def follow_me(d, k):
while k in d:
k = d[k]
return k
Note that the loop in this function will run forever if there is a cycle between keys and values in your dictionary. Your example has one between 'lion' and 'zebra', and it's not entirely clear how you intend such a cycle to be broken. If you want to expand each key only once, you could handle it by keeping track of the values you've seen so far in a set:
def follow_me(d, k):
seen = set()
while k in d and k not in seen:
seen.add(k)
k = d[k]
return k
This will return whichever key in the cycle you reach first (so follow_me(d, 'zebra') with your example dictionary will return 'zebra' after going zebra => lion => zebra). If you want some other outcome, you'd need different logic and it might be tricky to do.
If you request a key that's not in the dictionary (like 'aardvark' in your example), the requested key will be returned immediately. You could add special handling for the first key you look up, but it would again make things more complicated.
Considering the existence of infinite loops this has to be handled. Your description isn't clear about what should happen in this case.
def follow_me(d, key):
visited_keys = []
while key not in visited_keys and d[key]:
visited_keys.append(key)
key = d[key]
if not d[key]:
return key
return "this hunt has no end"
I have a function that loops through a JSON object. The object often comes back in several different formats and I need to find a specific key and print the value of it. Also, sometimes the key I need is listed multiple times. So, I only want to print the first one. I've tried using a break but it doesn't seem to work. Any ideas why?
def deep(o):
for k, v in o.iteritems():
if k.lower() == 'key_i_look_for':
print v
break
elif type(v) is dict:
deep(o[k])
elif type(v) is list:
for i in v:
if type(i) is dict:
deep(i)
Although break works just fine, you are also recursing through a nested structure and never returning anything. You are ignoring the recursive searches in the outer calls; if one of them finds the key, the next recursive call is still executed.
You need to return recursive calls too, and take into account that some searches may not yield anything (return None):
def deep(o):
for k, v in o.iteritems():
if k.lower() == 'key_i_look_for':
return v
if not isinstance(v, list):
v = [v]
for i in v:
if isinstance(i, dict):
result = deep(i)
if result is not None:
return result
I've cleaned up the logic a little to handle list vs. dictionary values a little easier, and switched to using isinstance() to allow for subclasses too.
This version returns the first key it finds; any recursive calls are checked for None to see if that recursive call turned up something, and break of the search there.
I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays ONLINE without anything aside from the display the message. Any ideas why ?
def isEmpty(self, dictionary):
for element in dictionary:
if element:
return True
return False
def onMessage(self, socket, message):
if self.isEmpty(self.users) == False:
socket.send("Nobody is online, please use REGISTER command" \
" in order to register into the server")
else:
socket.send("ONLINE " + ' ' .join(self.users.keys()))
Empty dictionaries evaluate to False in Python:
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
Thus, your isEmpty function is unnecessary. All you need to do is:
def onMessage(self, socket, message):
if not self.users:
socket.send("Nobody is online, please use REGISTER command" \
" in order to register into the server")
else:
socket.send("ONLINE " + ' ' .join(self.users.keys()))
Here are three ways you can check if dict is empty. I prefer using the first way only though. The other two ways are way too wordy.
test_dict = {}
if not test_dict:
print "Dict is Empty"
if not bool(test_dict):
print "Dict is Empty"
if len(test_dict) == 0:
print "Dict is Empty"
d = {}
print(len(d.keys()))
If the length is zero, it means that the dict is empty.
Simple ways to check an empty dict are below:
a = {}
if a == {}:
print ('empty dict')
if not a:
print ('empty dict')
Method 1 is more strict, because when a = None, method 1 will provide the correct result, but method 2 will give an incorrect result.
A dictionary can be automatically cast to boolean which evaluates to False for empty dictionary and True for non-empty dictionary.
if myDictionary: non_empty_clause()
else: empty_clause()
If this looks too idiomatic, you can also test len(myDictionary) for zero, or set(myDictionary.keys()) for an empty set, or simply test for equality with {}.
The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.
The return False statement is indented one level too deep. It should be outside the for loop and at the same level as the for statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives.
If the dictionary is not empty, then the code will process only one key and return its value cast to boolean. You cannot even assume that the same key is evaluated each time you call it. So there will be false positives.
Let us say you correct the indentation of the return False statement and bring it outside the for loop. Then what you get is the boolean OR of all the keys, or False if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.
myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}
1st Way
len(given_dic_obj)
It returns 0 if there are no elements.
Else, returns the size of the dictionary.
2nd Way
bool(given_dic_object)
Returns False if the dictionary is empty, else return True.
You can also use get(). Initially I believed it to only check if key existed.
>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool(d.get('c'))
False
>>> d['c']['e']=1
>>> bool(d.get('c'))
True
What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.
use 'any'
dict = {}
if any(dict) :
# true
# dictionary is not empty
else :
# false
# dictionary is empty
In my Ruby application I have a hash table:
c = {:sample => 1,:another => 2}
I can handle the table like this:
[c[:sample].nil? , c[:another].nil? ,c[:not_in_list].nil?]
I'm trying to do the same thing in Python. I created a new dictionary:
c = {"sample":1, "another":2}
I couldn't handle the nil value exception for:
c["not-in-dictionary"]
I tried this:
c[:not_in_dictionery] is not None
and it is returning an exception instead of False. How do I handle this?
In your particular case, you should probably do this instead of comparing with None:
"not_in_dictionary" in c
If you were literally using this code, it will not work:
c[:not_in_dictionary] is not None
Python doesn't have special :keywords for dictionary keys; ordinary strings are used instead.
The ordinary behaviour in Python is to raise an exception when you request a missing key, and let you handle the exception.
d = {"a": 2, "c": 3}
try:
print d["b"]
except KeyError:
print "There is no b in our dict!"
If you want to get None if a value is missing you can use the dict's .get method to return a value (None by default) if the key is missing.
print d.get("a") # prints 2
print d.get("b") # prints None
print d.get("b", 0) # prints 0
To just check if a key has a value in a dict, use the in or not in keywords.
print "a" in d # True
print "b" in d # False
print "c" not in d # False
print "d" not in d # True
Python includes a module that allows you to define dictionaries that return a default value instead of an error when used normally: collections.defaultdict. You could use it like this:
import collections
d = collections.defaultdict(lambda: None)
print "b" in d # False
print d["b"] # None
print d["b"] == None # True
print "b" in d # True
Notice the confusing behaviour with in. When you look up a key for the first time, it adds it pointing to the default value, so it's now considered to be in the dict.