Reputation: 442
I have a dictionary: dict = {"key":[None, "item 2", "item 3"]}
How can I check that dict["key"][0] is None
if "key" is unknown.
I have this so far:
{k: dict[k][0] for k in dict.viewkeys()}
which gives me:
{"key":None}
In my application, I am testing to see if dict["key"][0]
has been populated yet, its default is None.
Upvotes: 1
Views: 76
Reputation: 10397
Not the safest/cleanest:
if d[d.keys()[0]][0] is None: print "Empty"
Upvotes: 0
Reputation: 1720
perhaps try filter(lambda k: dict[k][0] == None, dict.keys())
should return a list of all the members of dict.keys() (the list of keys) whose first element is None (that is, they return True for dict[k][0] == None)
Upvotes: 0
Reputation: 151007
You're very close. If you want all key, value pairs such that the first item in the value list is None
, you could do this:
unassigned_items = {k:v for k, v in mydict.viewitems() if v[0] is None}
Note that you shouldn't use dict
as a variable name because it masks the dict
built-in -- even in example code, if only because it may mislead people.
Once you've got unassigned_items
, you can simply test to see if 'key'
is in unassigned_items
:
if key in unassigned_items:
do_something()
Upvotes: 2