如何通过使用Python字典中的fromkey()选择特定键来创建新字典?

我创建了名为Colors的字典。

Colors = {'col1': 'Red','col2': 'Orange','col3': 'Yellow','col4': 'Yellow'} 

Q)从颜色Dictionary中创建一个新的Dictionary对象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','col4': 'Yellow'}
{}
{'col1': None,'col2': None,'col3': None,'col4': None}
gaoshao1982 回答:如何通过使用Python字典中的fromkey()选择特定键来创建新字典?

是的,确实有可能。

colors_new = dict.fromkeys(Colors.keys()[:2])
,

这也许是您想要的吗?

Colors = {'col1': 'Red','col2': 'Orange','col3': 'Yellow','col4': 'Yellow'}
print(Colors)
Col={ }
Colors_new={ }
print(Colors_new)
# if you want the new dictionary with only the keys
Colors_new = dict.fromkeys([k for k in Colors.keys() if k in ["col1","col2"]])
print(Colors_new)
# if you want the new dictionary with keys and values
Colors_new = {k:v for k,v in Colors.items() if k in ["col1","col2"]}
print(Colors_new)
本文链接:https://www.f2er.com/3138574.html

大家都在问