[Tutor] slicing nested lists/dicts/tuples
Brian van den Broek
bvande at po-box.mcgill.ca
Tue Jun 28 22:14:05 CEST 2005
Luis N said unto the world upon 28/06/2005 15:25:
> Hi,
>
>
>>>>l
>
> [{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, {'last':
> 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}]
>
>
> This is how I imagine it:
>
> for i in l:
> for j in l[i]:
> for k in l[i][j]:
> print k.get('first')
> print k.get('last')
>
> Is there a short and sweet way of doing this (that actually works).
>
> Luis.
Hi Luis,
I'm not certain I see what you are wanting from your description.
(You've got more nesting in your loops than in l.) But does this do
what is wanted?
>>> a_list = [ {'last': 'Bar', 'first': 'Foo'},
{'last': 'Bar', 'first': 'Foo'},
{'last': 'Bar', 'first': 'Foo'},
{'last': 'Bar', 'first': 'Foo'} ]
>>> for a_dict in a_list:
print a_dict['first']
print a_dict['last']
Foo
Bar
Foo
Bar
Foo
Bar
Foo
Bar
>>>
If it does, why are you doing this? Is it to figure out how to
manipulate data structures with Python? If so, good. If you are trying
to do real work this way, there is surely a better way. Maybe if you
said what you are trying to accomplish, someone could help you find a
good way to do it.
Best,
Brian vdB
More information about the Tutor
mailing list