Am 07.08.2011 17:37, schrieb Kayode Odeyemi:
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}";
This is not a dict, it's a tuple of two strings. (By the way, the ";" is
only needed if you would want to place several statements in one line,
which you shouldn't do.)
A tuple of dicts would be:
x = {'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel':
3456}}, {'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, 'tel':
34510}}
Note the additional closing "}" for each entry. You can loop over the
entries of your tuple and check the type:
for entry in x:
print type(entry)
Now you can extend this loop and loop over the keys and values for each
entry:
for entry in x:
for key, value in entry.items():
print key
print value
If key is "fields" then value is another dictionary. So if you wish you
could also get the entries of those dicts explicitly:
for entry in x:
for key, value in entry.items():
print key
if key == "fields":
for field_key, field_value in value.items():
print " %s" % field_key
print " %s" % field_value
else:
print " %s" % value
For string formatting used here see:
http://docs.python.org/library/stdtypes.html#string-formatting-operations
HTH,
Jan
#loop through and get the keys of each
for k,v in x:
keys = dict(x).keys()
print keys
I get ValueError: too many values to unpack
Any help will be much appreciated.
Regards
--
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor