Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
simple key value loop help
#1
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 :)
Reply
#2
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".
Reply
#3
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])
Reply
#4
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']
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
thank you all, this definitely helps me understand dictionary more, appreciate everyone's time and input.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Seemingly simple loop Weber585 7 3,501 Mar-21-2021, 07:19 PM
Last Post: jefsummers
  Simple Variable Saving in Loop DevDev 3 3,009 Mar-09-2021, 07:17 PM
Last Post: Fre3k
  simple for loop? gr3yali3n 3 2,521 Sep-22-2020, 05:35 AM
Last Post: buran
  Adding second message to simple loop error PythonGainz 2 2,085 Apr-06-2020, 11:55 AM
Last Post: PythonGainz
  Simple while loop only works on first attempt jsb83 2 2,017 Jun-20-2019, 08:57 PM
Last Post: jsb83

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020