0

嗨,我有类似的东西

pq={<Timestamp: 2008-02-02 13:30:46>: {('1059', 'latitude'): 40.064889999999998,
                                ('1059', 'longitude'): 116.56359,
                                ('1466', 'latitude'): 39.92163,
                                ('1466', 'longitude'): 116.32633,
                                ('1563', 'latitude'): 39.864249999999998,
                                ('1563', 'longitude'): 116.39328,
                                ('1827', 'latitude'): 40.003770000000003,
                                ('1827', 'longitude'): 116.30907000000001}}

我想要类似的东西

pq={<Timestamp: 2008-02-02 13:30:46>: {'1059':{'latitude: 40.064889999999998,'longitude': 116.56359},
                                       '1466' :{'latitude': 39.92163,'longitude': 116.32633},
                                       '1563':{'latitude': 39.864249999999998, 'longitude':116.39328},
                                       '1827':{'latitude': 40.003770000000003,'longitude': 116.30907000000001}}

我怎么做?

4

1 回答 1

0

您想通过拆分元组键来进行细分。

为了自动创建 subdicts,请使用defaultdict.

遍历要修改的字典项允许您使用元组解包来拆分元组键:

>>> import collections
>>> subpq = collections.defaultdict(dict)
>>> for (number, type), value in pq.values()[0].items():
...  subpq[number][type] = value
... 
>>> subpq
defaultdict(<type 'dict'>,
            {'1059': {'latitude': 40.06489, 'longitude': 116.56359},
             '1827': {'latitude': 40.00377, 'longitude': 116.30907},
             '1563': {'latitude': 39.86425, 'longitude': 116.39328},
             '1466': {'latitude': 39.92163, 'longitude': 116.32633}})
于 2013-04-20T16:39:33.243 回答