【问题标题】:How to create new dictionary by selecting particular keys using fromkey() in python Dictionary?如何通过在 python 字典中使用 fromkey() 选择特定键来创建新字典?
【发布时间】: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


【解决方案1】:

是的,这确实是可能的。

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

【讨论】:

  • 不。我只需要 col1 和 col2。
  • 在使用字典切片时,出现如下错误.. .. .. TypeError: 'dict_keys' object is not subscriptable
【解决方案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)

【讨论】:

  • 干得好。坦奇。我需要澄清的另一件事是......是否可以在使用 fromkeys() 时创建没有“none”的新字典。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2014-09-13
  • 2019-01-16
  • 2023-02-03
  • 1970-01-01
  • 2021-01-15
相关资源
最近更新 更多