views:

63

answers:

3

How can i have a tuple that has a list as a value.

F.x. if i want to have a structure like this.

( Somechar , Somelist[] )

And how would i iterate through a dictionary of these things?

A: 

A tuple can contain anything you like. It just works the same as a nested list.

>>> myvar = ('d', [1, 2])
>>> myvar[0]
'd'
>>> myvar[1]
[1, 2]
>>> myvar[1][1]
2
Daniel Roseman
+2  A: 

You can add a list to a tuple just like any other element. From a dictionary, you can access each element of the tuple by indexing it like so: d[key][0] and d[key][1]. Here is an example:

>>> d = {}
>>> d["b"] = ('b', [2])
>>> d["a"] = ('a', [1])
>>> for k in d:
...     print(d[k][0], d[k][1])
...
('a', [1])
('b', [2])
Justin Ethier
If you need to iterate through all a number of variable elements, just do a for `for element in d['a']: print d['a'], element`
Khelben
Yes, this answers it... thanks ;)
Johann
A: 

Here's a simple example:

>> a = ('a', ['a list'])
>> a
('a', ['a list'])
>> b = dict((a,))
{'a': ['a list']}

for i, j in b.iteritems():
    print i, j

a ['a list']

Does that answer your question? The dict constructor takes a list/tuple of (key, value) tuples. Also keep in mind the ',' character is constructor for a tuple (not just the () ).

rlotun