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

Kayode Odeyemi dreyemi at gmail.com
Mon Aug 8 10:18:06 CEST 2011


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


On Sun, Aug 7, 2011 at 5:45 PM, Steve Willoughby <steve at alchemy.com> wrote:

> On 07-Aug-11 09:17, Steve Willoughby wrote:
>
>  First of all, that's not a dict. It's just a tuple of strings.
>> so, when you say:
>>
>>  #loop through and get the keys of each
>>> for k,v in x:
>>>
>>
>> You'll get one iteration, where k=the first string and v=the second.
>> However, you ignore k and v in all the code that follows, so I'm really
>> confused what you're trying to do here.
>>
>
> I just noticed I glossed over a key point, for that to work you'd need x to
> be a sequence of such tuples.  As it stands there, you'll get an error
> because each element of x is a single string, so it can't pull two values
> out of each of them.
>
>
> --
> 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
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110808/78834fbc/attachment-0001.html>


More information about the Tutor mailing list