1

我正在尝试迭代 Python 中的嵌套有序字典。我知道我可以做这样的事情:

food = OrderedDict([('Fruits', OrderedDict([('Apple', 50), ('Banana', 100), ('Pear', 200)])), 
                    ('Vegetables', OrderedDict([('Carrot', 10), ('Broccoli', 5), ('Corn', 40)]))])
for value in food.itervalues():
    for key in value.iterkeys():
        print key

使用嵌套的 for 循环获取键(或值)。但是,我怎样才能在一行中做到这一点?我试图只将字符串键(即水果名称)保存到熊猫数据框(不使用数字)。这是我的尝试:

food_df = pd.DataFrame({'Food': key for key in value.iterkeys() for value in food.itervalues()})

这引发了错误:

File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 397, in __init__
    mgr = self._init_dict(data, index, columns, dtype=dtype)
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 528, in _init_dict
    dtype=dtype)
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 5670, in _arrays_to_mgr
    index = extract_index(arrays)
File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 5708, in extract_index
    raise ValueError('If using all scalar values, you must must pass'
    ValueError: If using all scalar values, you must must pass an index

有任何想法吗?谢谢!

4

1 回答 1

3
[item for sublist in map(lambda a: a.keys(), food.itervalues()) for item in sublist]

这返回

['Apple', 'Banana', 'Pear', 'Carrot', 'Broccoli', 'Corn']

在你的情况下。

然后,您可以像往常一样创建一个 DataFrame。

food_pd = pd.DataFrame([item for sublist in map(lambda a: a.keys(), food.itervalues()) for item in sublist], columns=["Food"])
于 2014-03-12T15:10:39.323 回答