On 07-Aug-11 08:37, Kayode Odeyemi wrote:
Hello all,

Please I need help figuring out this permutation.

I have a dict like this:

x = "{'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel':
3456}", "{'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011,
'tel': 34510}";

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.

     keys = dict(x).keys()

Now you try to create a dict out of a tuple of strings, which won't quite work as written but in principle would only have created a dictionary with the first string as the key, and the second as value, not nested dictionaries.

The dict() constructor really expects to see a sequence of key/value pairs, so it's going to take your sequence x as a list of two such pairs, and then raise an exception because the strings are not key/value pairs. This would succeed if you said
  keys = dict((x,)).keys()
perhaps, but it's still not at all what you're trying to accomplish.

print keys

Note that you are re-assigning the value of keys each time through the loop but printing its last value after the loop exits. Is that what you intended?


You're expecting Python to take a string that looks like Python source code and know that you want it to be interpreted as source code. Instead of using string values, use actual Python syntax directly, like:

 x = {
        'pk': 1L,
        'model': 'trans',
        'fields': {
                'updated': 2011,
                'tel': 3456
        }
}


--
Steve Willoughby / [email protected]
"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  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to