-1

How d[key] is getting dictionary values in for loop? I know the other way to write dictionary code in for loop is:

d = {'a': 1, 'b': 2, 'c': 3} 
for key, values in d.items():
    print (key, 'corresponds to', values)

But I want to know how in below for loop how d[key] is getting values. Is there dictionary values are getting convert to list? Please help me here.

d = {'a': 1, 'b': 2, 'c': 3} 
for key in d:
    print (key, 'corresponds to', d[key])
DYZ
  • 55,249
  • 10
  • 64
  • 93

2 Answers2

0

When you simply iterate over a dict like that, you are actually iterating over the keys of the dictionary. For example:

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> list(d)
['a', 'b', 'c']

Then, d[key] accesses the value at the specified key in the dictionary.

iz_
  • 15,923
  • 3
  • 25
  • 40
0

It' because in the second snippet you are accessing directly the dict (d[key]):

d = {'a': 1, 'b': 2, 'c': 3} 
for key in d:
  print(key) # <-- see the output
  print (key, 'corresponds to', d[key])

d.items() is a kind of helper which returns the pair key, value:

print(d.items()) #=> dict_items([('a', 1), ('b', 2), ('c', 3)])

Something like:

lst = [(1,2), (2,4)]
for k,v in lst:
  print(k, v)
iGian
  • 11,023
  • 3
  • 21
  • 36
  • I have another question, in a list x=[1,2,3,4,5,6,7,4,4,3,2,1] how can I get second in last record of 4 using loop. – TARUN PUNETHA Jan 04 '19 at 06:36
  • @TARUN PUNETHA, I think I don’t completely understand your question. – iGian Jan 05 '19 at 06:35
  • thanks for help earlier, I was asking to remove duplicates from a list. Sorry for confusion.I searched in stack overflow and I got answer, using set() function duplicates can be removed. – TARUN PUNETHA Jan 07 '19 at 06:45