You should iterate over keys with:
Copyfor key in mydictionary:
print "key: %s , value: %s" % (key, mydictionary[key])
Answer from systempuntoout on Stack OverflowYou should iterate over keys with:
Copyfor key in mydictionary:
print "key: %s , value: %s" % (key, mydictionary[key])
If you want to access both the key and value, use the following:
Python 2:
Copyfor key, value in my_dict.iteritems():
print(key, value)
Python 3:
Copyfor key, value in my_dict.items():
print(key, value)
Is there a way to find a key in a dictionary with only knowing the value?
What is the most pythonic way of getting an object from a dict when the key may not exist?
What does get() mean and do in Python?
When to use dict.get in Python (timing)
Videos
For example, I have the dictionary {Sam: 93, bob: 23}
And I want to know which people have got 93 % in the course.
How can I do this?
QUESTION:
There are two ways to get an item from a dict. Referencing the item with "dict[key]" or calling "dict.get(key)".
If the item doesn't exist, dict[key] raises KeyError, whereas dict.get(key) return None.
Which of these is more pythonic?
try:
value = dict\[key\]
except KeyError as ke:
\# Do something elseOr
value = dict.get(key) if value == None: \# Do the thing else: \# Do something else
==========================================
UNNECESSARY CONTEXT FOR COMPLETIONISTS:
I am writing a program that imports objects and maps their relationships as a tree.
Part of the processing involves a dict that tracks partial relationships between entities. If I have already processed the item's parent, then it's easy for me to look up the parent's entire path to the root of the tree in a dict based on the parent's identifier. Then I just create a new dict entry which is "parent's path + child". Usually, this works, but sometimes the object's parent hasn't been processed yet. I do some special processing when I detect that the parent's path hasn't been discovered.