简体   繁体   English

Function 只打印字典的最后 2 个键:值对

[英]Function only printing last 2 key:value pairs of dictionary

I'm creating a function that takes a dictionary as a parameter.我正在创建一个将字典作为参数的 function。 The dictionary is made up of a key which is a last name and a value is a list of first names.字典由一个键组成,键是姓,值是名字的列表。

The function should return a new dictionary where each key is the first letter of the key in the parameter, and the value is the number of items in the value of the parameter function 应该返回一个新字典,其中每个键是参数中键的第一个字母,值是参数值中的项目数

Example例子

names = {"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Lannister": ["Jaime", "Cersei", "Tywin"]}

{"S" : 3, "S" : 1,  "L": 3}

The function I've written is only printing '{'S': 1, 'L': 3}' the last 2 key, value pairs in the dictionary but I want {'S': 3, 'S': 1, 'L': 3} printed我写的 function 只打印 '{'S': 1, 'L': 3}' 字典中的最后 2 个键值对,但我想要 {'S': 3, 'S': 1, 'L': 3} 打印

def count_first_letter(names):
     beginning = []
     last = []
     for element, number in names.items():
       amount = len(number)
       first = element[0]
       last.append(amount)
       beginning.append(first)
    
     new = {key:value for key, value in zip(beginning, last)}
    
    
     return new
    
    
    
    print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow": ["Jon"], "Lannister": ["Jaime", "Cersei", "Tywin"]}))

'{'S': 1, 'L': 3}'

Because 2 of your last names start with same letter: Stark, Snow.因为您的两个姓氏以相同的字母开头:Stark,Snow。 Thus, overwriting each other as dictionary keys are unique.因此,作为字典键相互覆盖是唯一的。

Your dictionary keys are getting overridden, so 'S': 3 is getting overridden by 'S': 1 because a dictionary cannot contain duplicate keys您的字典键被覆盖,因此'S': 3'S': 1覆盖,因为字典不能包含重复的键

To fix your problem, you would need to put them in a list like this:要解决您的问题,您需要将它们放在这样的列表中:

new = [(key,value) for key, value in zip(beginning, last)]

output: output:

[('S', 3), ('S', 1), ('L', 3)] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM