-1

I would like to create dictionary of the format in the example below.

c={
    'A':{('AB',2.9)},
    'B':{('AS',3.9)},
    'R':{('D',2.0)},
    'V':{('AD',2.9)},
    'G':{('AX',2.9)}
 }

I have this tuples feed in a loop. Here is what I have tried but I get a wrong format from this.

my_tuple  = ('AB',2.9)
c         = {}
my_key    = 'A'
c.update({my_key:{my_tuple}})

For this specific case I would like to get {'A': set([('AB', 2.9)])}. I understand this is a proper dictionary but how can do it better and return value of c in a format?. I want i.e.:

{'A': {('AB', 2.9)}}
4

2 回答 2

2

s = {1, 2, 3}是一种较短的声明方式 s = set([1,2,3])

因此,你已经得到了你想要的,这只是一个代表问题。

>>> {('AB',2.9)} == set({('AB',2.9)})
True
于 2013-03-24T08:54:23.393 回答
1

如果表示对您来说很重要,您可以继承set并创建您自己的版本,__repr__这将使您可以自由地使用您的想象力来满足您:-)

>>> class funky_set(set):
    def __new__(cls,*args):
        return set.__new__(cls,args)
    def __repr__(self):
        return "{{{}}}".format(','.join(map(str, self)))

>>> my_tuple  = ('AB',2.9)
>>> c         = {}
>>> my_key    = 'A'
>>> c.update({my_key:funky_set(my_tuple)})
>>> c
{'A': {AB,2.9}}
于 2013-03-24T08:59:43.180 回答