【发布时间】:2019-11-08 10:45:44
【问题描述】:
我创建了名为 Colors 的字典。
Colors = {'col1': 'Red', 'col2': 'Orange', 'col3': 'Yellow', 'col4': 'Yellow'}
Q) 从颜色字典中创建一个新的字典对象colors_new,具有键 col1 和 col2(说明 - 使用 fromkeys() 方法)?可以使用fromkeys()吗?
我的编码是:
颜色 = {'col1': '红色', 'col2': '橙色', 'col3': '黄色', 'col4': '黄色'}
print(Colors)
Col={ }
Colors_new={ }
print(Colors_new)
Colors_new = dict.fromkeys(Colors.keys())
print(Colors_new)
输出
{'col1': 'Red', 'col2': 'Orange', 'col3': 'Yellow', 'col4': 'Yellow'}
{}
{'col1': None, 'col2': None, 'col3': None, 'col4': None}
【问题讨论】:
-
欢迎来到 SO。这似乎是一个程序任务。到现在为止你做了什么?向我们展示您的尝试,然后我们可以从他们开始
-
我假设你想要类似 colors_new = dict.fromkeys(colors.keys())
-
我的 Colors_new 中只需要 col1 和 col2
标签: python dictionary-comprehension fromkeys