Johann
Johann

Reputation: 3

Dictionaries with tuples that have lists as values

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?

Upvotes: 0

Views: 235

Answers (3)

rlotun
rlotun

Reputation: 8063

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 () ).

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134177

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])

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599610

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

Upvotes: 0

Related Questions