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

Peter Otten __peter__ at web.de
Tue Aug 9 09:10:00 CEST 2011


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
> 2011 3456
> 2011 34510
> 
> right now, I'm having it displayed as
> 
> updated
> 2011
> tel
> 3456
> updated
> 2011
> tel
> 34510
> 
> I am having the fields being written using a writer like this:
> 
> x = {'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel':
> 3456}},
> {'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, 'tel': 34510}}
> writer = csv.writer(response)
> 
> for entry in x:
>    for key, value in entry.items():
>        print key
>        if key == "fields":
>            for field_key, field_value in value.items():
>                d = [field_key] #a list of sequence
>                x = [field_value]
>        writer.writerow(d)
>                writer.writerow(x)
>        else:
>            print "  %s" % value

You are doing too much at once. You are only interested in the "fields" 
dictionary, so I recommend that you extract that first:

items = [
    {'pk': 1, 'model': 'trans', 'fields': {'updated': 2011, 'tel': 3456}},
    {'pk': 2, 'model': 'trans2', 'fields': {'updated': 2011, 'tel': 34510}}
]

rows = [item["fields"] for item in items]

Now the data structure has become simpler, just a list of dictionaries, you 
can think about how you generate the output. One way, the str.format() 
method, was already mentioned:

>>> for row in rows:
...     print "{updated}\t{tel}".format(**row)
...
2011    3456
2011    34510

If you want to continue to use the csv module you should use the DictWriter:

>>> import csv, sys
>>> fieldnames = rows[0].keys()
>>> writer = csv.DictWriter(sys.stdout, fieldnames)
>>> writer.writeheader()
updated,tel
>>> writer.writerows(rows)
2011,3456
2011,34510




More information about the Tutor mailing list