Python Forum

Full Version: simple key value loop help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have the following python code:

d = {'123':'John','123':'Steve','4929':'959','3491':'5','319':'Bob','name': 'john','code':6734, 'dept': 'sales'}

for k, v in d.items():
   if(k == '123'):
    print (v)
and the results should print out 2: which are Steve and John, however i only see steve printed out... not sure why? any help would be great.

thanks in advance :)
A dictionary is a collection of key->value pairs. Duplicate keys don't make sense, so the last one evaluated is the one that will persist in the dict. ie: "John" isn't there, because you overwrote it with "Steve".
Hi dear,
If you want to print both the name with same value(or key value) then, you have to change your data type from dictionary to something like tuple , because you can keep the identically values there
hope it may help you.
for example :-
d = [(1,'abc'),(1,'xyz')]
for i in d:
    if i[0] == 1:
       print (i[1])
You don't need to iterate over dictionary. You should go directly to key and associated value:

>>> d = {'123': 'John', '319': 'Bob'} 
>>> print(d['319'))
Bob
I also suggest to think whether current structure of data is suitable for task at hand. For example you can have list (or tuple) as value:

>>> d = {'123': ['John', 'Steve'], '319': ['Bob']}
>>> print(*d['123'])
John Steve
>>> ', '.join(d['123'])
John, Steve
>>> ', '.join(d['319'])
Bob
You can also have list of named tuples or dictionaries. Then you can iterate over list and look for match:

>>> d = [{'name': 'John', 'code': 123},
...      {'name': 'Steve', 'code': 123},
...      {'name': 'Bob', 'code': 319}]
>>> [record['name'] for record in d if record['code'] == 123]
['John', 'Steve']
thank you all, this definitely helps me understand dictionary more, appreciate everyone's time and input.