0

I have this dict below and I am not sure how to loop it through to get the correct data that I want,

py_dict = {'age': {0: 10, 1: 30.0, 2: 19.0}, 'name': {0: u'Michael', 1: u'Andy', 2: u'Justin'}}

for item in py_dict:
    print("Name:",item[0])
    print("Age:", item[1])
    print("")

Result,

('Name:', 'a')
('Age:', 'g')

('Name:', 'n')
('Age:', 'a')

But what I want is,

Name: Michael
Age:  10

Name: Andy
Age:  30

and so on....

EDIT:

py_dict = pandas_df.to_dict()
print py_dict

   age     name
0  NaN  Michael
1   30     Andy
2   19   Justin
1

4 Answers 4

2

You are thinking about looping through dictionaries wrongly, when you do -

for i in dict:

i is actually the key in the dictionary , not the value. Example -

>>> d = {1:2,3:4}
>>> for i in d:
...     print(i)
...
1
3

As you can see , it printed the keys not the values. So if you need the keys as well as values, iterate over iteritems() (for Python 2.x) , or items() (for Python 3.x) . Both return a list of tuples where the first element of tuple is the key and second element is the value.

Secondly, after that, you are only getting the dictionaries for each name as well as age separately , if you want to get them together, I would suggest going through the keys of one of them and getting name and age using that. Example -

py_dict = {'age': {0: 10, 1: 30.0, 2: 19.0}, 'name': {0: u'Michael', 1: u'Andy', 2: u'Justin'}}

for key in py_dict['name']:
    print "Name:",py_dict['name'][key]
    print "Age:", py_dict['age'][key]
    print

Example/Demo -

>>> py_dict = {'age': {0: 10, 1: 30.0, 2: 19.0}, 'name': {0: u'Michael', 1: u'Andy', 2: u'Justin'}}
>>> 
>>> for key in py_dict['name']:
...     print "Name:",py_dict['name'][key]
...     print "Age:", py_dict['age'][key]
...     print
... 
Name: Michael
Age: 10

Name: Andy
Age: 30.0

Name: Justin
Age: 19.0

Another note, you seem to be using Python 2.x , in which case print is a statement , not a function, if you want the print function, you would need to do - from __future__ import print_function . But you do not really need them, use them as statements, as I did above.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the details answer!
2

Using the same dictionary, this method also works.

py_dict = {'age': {0: 10, 1: 30.0, 2: 19.0}, 'name': {0: u'Michael', 1: u'Andy', 2: u'Justin'}}

for index, name in py_dict['name'].items():
    print("Name: " + name)
    print("Age: " + str(py_dict['age'][index]))
    print("")

Comments

1

If you have to keep your data structured that way, do:

#!/usr/bin/env python3
py_dict = {'age': {0: 10, 1: 30.0, 2: 19.0}, 'name': {0: u'Michael', 1: u'Andy', 2: u'Justin'}}

for i in range(len(py_dict['age'])):
    print('Name: ', py_dict['name'][i]);
    print('Age: ', py_dict['age'][i]);

But it would be better to refactor your code like:

#!/usr/bin/env python3
py_dict = [{'age':10,'name':'Michael'},{'age':30,'name':'Andy'},{'age':19,'name':'Justin'}]

for item in py_dict:
    print('Name: ', item['name'])
    print('Age: ', item['age'])

2 Comments

Thanks. How can turn my data into this format - [{'age':10,'name':'Michael'},{'age':30,'name':'Andy'},{'age':19,'name':'Justin'}]? Please see my edit above
Oh, I was just saying that it would probably be better to keep the data in the second format if you were the one designing the format of your data. But since you aren't and the data is output from a database, it's fine to just use the first method
1

I think for dynamic purpose of dict and elements this code can work:

for j in py_dict.values():
    for k in j.keys():
        for i in py_dict.keys():
             print py_dict[i][k]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.