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[]开发者_StackOverflow中文版 )
And how would i iterate through a dictionary of these things?
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])
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
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 () ).
精彩评论