Python - loop a dictionary? -
i have dict below , not sure how loop through correct data want,
py_dict = {'age': {0: 10, 1: 30.0, 2: 19.0}, 'name': {0: u'michael', 1: u'andy', 2: u'justin'}} item in py_dict: print("name:",item[0]) print("age:", item[1]) print("") result,
('name:', 'a') ('age:', 'g') ('name:', 'n') ('age:', 'a') but want is,
name: michael age: 10 name: andy age: 30 , on.... edit:
py_dict = pandas_df.to_dict() print py_dict age name 0 nan michael 1 30 andy 2 19 justin
you thinking looping through dictionaries wrongly, when -
for in dict: i key in dictionary , not value. example -
>>> d = {1:2,3:4} >>> in d: ... print(i) ... 1 3 as can see , printed keys not values. if need keys values, iterate on iteritems() (for python 2.x) , or items() (for python 3.x) . both return list of tuples first element of tuple key , second element value.
secondly, after that, getting dictionaries each name age separately , if want them together, suggest going through keys of 1 of them , getting name , 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'}} 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'}} >>> >>> 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, seem using python 2.x , in case print statement , not function, if want print function, need - from __future__ import print_function . not need them, use them statements, did above.
Comments
Post a Comment