0

How can I iterate over my dictionary? I need to print details of every items.

my_dict = {
   'item':[
      {
         'date':'1990',
         'name':'test',
         'image':'/media/item/img.jpg',
         'desc':'Sample desc'
      },
      {
         'date':'1991',
         'name':'test1',
         'image':'/media/item/img1.jpg',
         'desc':'Sample desc1'
      }
   ]
}
user3115655
  • 109
  • 1
  • 2
  • 8

2 Answers2

1

Dictionary has the ability to iterate over itself to print each item. To simply print the details of each item as you have asked, simply use the print command:

>>> ourNewDict = {'name': 'Kyle', 'rank': 'n00b', 'hobby': 'computing'}
>>> print ourNewDict

Output: {'hobby': 'computing', 'name': 'Kyle', 'rank': 'n00b'}

Or, to print keys and values independently:

>>> print ourNewDict.keys()
Output: ['hobby', 'name', 'rank']
>>> print ourNewDict.values()
Output: ['computing', 'Kyle', 'n00b']

If I read into your question more, and guess that you'd like to iterate through each object to do more than simply print, then the items() command is what you need.

>>> for key, value in ourNewDict.items():
...     print key
... 
hobby
name
rank
>>> for key, value in ourNewDict.items():
...     print value
... 
computing
Kyle
n00b
>>> 

And to be very generic:

>>>for someVariableNameHere in someDictionaryNameHere.items():
...     doStuff
KyleM
  • 508
  • 2
  • 4
  • 11
0

You iterate through a dictionary just like an array, but instead of giving you the values in the dictionary it gives you the keys.

> my_dict = {"a" : 4, "b" : 7, "c" : 8}
> for i in my_dict:
...  print i

a
b
c

You can then access the data in the dictionary like you normally would. (This is achieved with square brackets, so my_dict["a"] would give 4.)

Yaiyan
  • 101
  • 7