是的,因为dict.items() 在 Python 3 中不再返回列表,而是返回一个特殊对象,该对象充当字典中项目的类似集合的 view(与 @ 相同) 987654323@ 和 .values)。最简单的解决方法就是执行list(dict.items())。
但是,在这种特殊情况下,dict({'index': row}.items() + row_colors[row].items()) 在 python 3 中可能只是 {'index':row, **row_colors[row]}。
所以你可以使用:
para['row_colors'] = pd.DataFrame([{'index': row, **row_colors[row]} for row in table.index]).set_index('index')'
使用更现代的语法。
要了解以前的版本在做什么,请注意dict 构造函数接受可迭代的键值对:
>>> dict([('a', 1), ('b', 2)])
{'a': 1, 'b': 2}
由于 .items() 用于返回键值对列表,因此您可以执行类似的操作
dict(d1.items() + d2.items())
合并两个字典。要将其音译为 Python 3,您需要类似以下内容:
>>> d1 = {'foo': 'bar', 'baz': 'zing'}
>>> d2 = {"apple": 42}
>>> dict(list(d1.items()) + list(d2.items()))
{'foo': 'bar', 'baz': 'zing', 'apple': 42}
但是python 3有更方便的语法,你可以这样做:
>>> {**d1, **d2}
{'foo': 'bar', 'baz': 'zing', 'apple': 42}
或者,更灵活地使用特定的键值对:
>>> {'index': 'column1', **d1, 'frob': 'bob', **d2}
{'index': 'column1', 'foo': 'bar', 'baz': 'zing', 'frob': 'bob', 'apple': 42}
最后,请注意 Python 3.9 will be adding the | operator as a merge operator for dicts,允许非常简洁:
>>> d1 | d2
{'foo': 'bar', 'baz': 'zing', 'apple': 42}
对于最简单的情况