Mokus
Mokus

Reputation: 10410

Get key from dictionary

I just started with Python,

Is there some iteration in dictionary like in PHP

foreach(aData as key=>value)

Upvotes: 4

Views: 445

Answers (3)

Cédric Julien
Cédric Julien

Reputation: 80851

It looks like something like this :

my_dict = {"key1": 1, "key2":2}
my_dict.items()       # in python < 3 , you should use iteritems()
>>> ("key1", 1), ("key2", 2)

so you can iterate on it :

for key, value in my_dict.items():
   do_the_stuff(key, value)

Upvotes: 9

Dan D.
Dan D.

Reputation: 74685

assuming python 2:

for key, value in aData.iteritems():

Upvotes: 5

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29131

Use:

for key in dictionary.keys()
    value = dictionary[key]
    #do something

OR:

for key,value in dictionary.items():
    #do something

Upvotes: 4

Related Questions