我正在尝试迭代 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
有任何想法吗?谢谢!