如何从嵌套字典更改为平面数组?

时间:2014-12-07 05:32:32

标签: python arrays dictionary

我想在python中改变它

之前:

{'NewYork': {'Paris': 12, 'Hawaii': 8, 'Tokyo': 11, 'Incheon': 12, 'LA': 2}, 
 'Beijing': {'Hongkong': 3, 'Cebu': 5},
 'Incheon': {'Cairo': 10, 'LA': 11, 'Tokyo': 1}, 
 'Tokyo': {'NewYork': 12, 'Paris': 14, 'LA': 9}}

之后:

[("NewYork","Paris",12),
 ("NewYork","Hawaii",8),
 ("Newyork","Tokyo",11),
 ("NewYork","Incheon",12),
 ("NewYork","LA",2),
 ("Beijing","HongKong",3),
 ("Beijing","Cebu",5),
 ("Incheon","Cairo",10),
 ("Incheon","LA",11),
 ("Incheon","Tokyo",1),
 ("Tokyo","NewYork",12),
 ("Tokyo","Paris",14),
 ("Tokyo","LA",9)]

我该怎么做?

3 个答案:

答案 0 :(得分:1)

>>> before = {'NewYork': {'Paris': 12, 'Hawaii': 8, 'Tokyo': 11, 'Incheon': 12, 'LA': 2},
...          'Beijing': {'Hongkong': 3, 'Cebu': 5}, 'Incheon': {'Cairo': 10, 'LA': 11, 'Tokyo': 1},
...          'Tokyo': {'NewYork': 12, 'Paris': 14, 'LA': 9}}
>>>
>>> print [(key,k,v) for key,val in before.iteritems() for k,v in val.iteritems()]

[('NewYork', 'Paris', 12), ('NewYork', 'LA', 2), ('NewYork', 'Hawaii', 8), ('NewYork', 'Incheon', 12), ('NewYork', 'Tokyo', 11), ('Beijing', 'Hongkong', 3), ('Beijin
g', 'Cebu', 5), ('Incheon', 'Cairo', 10), ('Incheon', 'Tokyo', 1), ('Incheon', 'LA', 11), ('Tokyo', 'NewYork', 12), ('Tokyo', 'Paris', 14), ('Tokyo', 'LA', 9)]

答案 1 :(得分:1)

您可以使用list comprehension和两次迭代创建一个数组:

>>> city_pairings = {'NewYork': {'Paris': 12,
...                              'Hawaii': 8,
...                              'Tokyo': 11,
...                              'Incheon': 12,
...                              'LA': 2},
...                  'Beijing': {'Hongkong': 3,
...                              'Cebu': 5},
...                  'Incheon': {'Cairo': 10,
...                              'LA': 11,
...                              'Tokyo': 1},
...                  'Tokyo': {'NewYork': 12,
...                            'Paris': 14,
...                            'LA': 9}}

>>> flat = [(city, other_city, value)
...         for city, pairings in city_pairings.iteritems()
...         for other_city, value in pairings.iteritems()]

>>> from pprint import pprint
>>> pprint(flat)
[('NewYork', 'Paris', 12),
 ('NewYork', 'LA', 2),
 ('NewYork', 'Hawaii', 8),
 ('NewYork', 'Incheon', 12),
 ('NewYork', 'Tokyo', 11),
 ('Beijing', 'Hongkong', 3),
 ('Beijing', 'Cebu', 5),
 ('Incheon', 'Cairo', 10),
 ('Incheon', 'Tokyo', 1),
 ('Incheon', 'LA', 11),
 ('Tokyo', 'NewYork', 12),
 ('Tokyo', 'Paris', 14),
 ('Tokyo', 'LA', 9)]

第二个城市并不完全符合您想要的顺序,因为字典根据某些方案对它们进行排序。为了让城市按照他们插入字典的顺序排列,你必须使用OrderedDict做其他事情。

答案 2 :(得分:0)

这样可以解决问题:

 dict.items()