【问题标题】:How can I count the keys in list of dictionaries? | python如何计算字典列表中的键? | Python
【发布时间】:2022-11-22 04:11:45
【问题描述】:

例如有一个列表:

list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'model': 'Skyline', 'year': 1969} ...]

我想数一数每个模型有多少个模型。我该怎么做?

顺便说一句,对于格式错误我很抱歉,我是新来的。

我试过这个方法:

model_count = {}

for i in list:
if i['Model'] in model_count:
  model_count[i] += 1
else:
  model_count[i] = 1

我得到了这个错误:TypeError: unhashable type: 'dict'

【问题讨论】:

标签: python list dictionary count each


【解决方案1】:

基本上,您可以遍历字典(列表中的元素)并计算每个字典有多少个键。 你可以使用Dictionary class keys() method

对于下一个问题,请尝试在代码部分添加您的代码。

【讨论】:

  • .keys() 方法不是必需的,并且(虽然还不完全清楚)OP 正在尝试计算 "Model" 键的值,而不是键的计数
【解决方案2】:

假设列表中的每个字典中都存在键“模型”,您可以使用它

my_list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'Model': 'Skyline', 'year': 1969}]

models = {}
for dictionary in my_list:
    model = dictionary['Model']
    models[model] = models.get(model, 0) + 1

print(models)

输出:

{'Mustang': 1, 'Skyline': 1}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多