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.
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.
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.
There is no such thing as a key without a value in a dict. You can just set the value to None, though.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With