[Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack

Steve Willoughby steve at alchemy.com
Mon Aug 8 10:41:25 CEST 2011

On 08-Aug-11 01:18, Kayode Odeyemi wrote:
> Thanks so much. This is exactly what I'm looking for. In addition, since
> fields is obviously a dict, I won't want to have to display it's keys
> repeatedly. Is there a way to get the keys once, have it displayed and
> used as columns, then it's values are displayed beneath it. Something like:
> updated tel
> 20113456
> 201134510

Sure.  You have to make the assumption that all the dictionaries in your 
list x have the same keys, or iterate over all of them, making a master 
list of all the keys you found.  Either way, once you have the list of 
the keys you want to display, print them out once as column headings, 
then iterate over the list, printing each key's value in the same order 
each time.

Another approach, if it seems like you're stuffing a lot of data into 
complex dictionary structures, is to turn this into a class.  That way 
you can define the attributes of each object and even implement a 
print() method (or at least define __str__() and/or __repr__() methods) 
to print each object sensibly.

Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C

More information about the Tutor mailing list