Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary doesn't have all the keys assigned, or items

I created the following dictionary

exDict = {True: 0, False: 1, 1: 'a', 2: 'b'} 

and when I print exDict.keys(), well, it gives me a generator. Ok, so I coerce it to a list, and it gives me

[False, True, 2] 

Why isn't 1 there? When I print exDict.items() it gives me

[(False, 1), (True, 'a'), (2, 'b')] 

Anyone have a guess about what's going on here? I'm stumped.

like image 991
Addem Avatar asked May 04 '16 03:05

Addem


People also ask

How do you get a list of all the keys in a dictionary in Python?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.

How do you add a key to a dictionary Python if not exists?

Add an item only when the key does not exist in dict in Python (setdefault()) In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value.

Can a dictionary have a key with no value?

There is no such thing as a key without a value in a dict. You can just set the value to None, though.


1 Answers

This happens because True == 1 (and False == 0, but you didn't have 0 as a key). You'll have to refactor your code or data somehow, because a dict considers keys to be the same if they are "equal" (rather than is).

like image 170
John Zwinck Avatar answered Sep 20 '22 08:09

John Zwinck