简体   繁体   English

python - 字典中有多个相同的键

[英]python - more than one identical key in dict

this is my code这是我的代码

#this is for the max Day of a month, without leap year 
day_month = {'Janauary': 31, 'February':28, 'March':31, 'April':30, 'May':31, 'June':30, 'July':31, 'August':31, 'September':30, 'October':31, 'November':30, 'December':31}
#this dict i get as Input
myCalendar = {'April':30, 'July':10, 'May':20, 'February':29, 'August':31, 'August':13, 'August':21}
#this is the desired month to work with
month = 'August'

print(month in myCalendar) # it shows that month exists in myCalendar  
print(myCalendar[month]) # this give the value
print('')

for i in myCalendar:
    print(str(i) + ' ' + str(myCalendar[i]))

these are the output这些是输出

True
21

#result of for loop
April 30
July 10
May 20
February 29
August 21  #the problem is this one, I want to have the max value of those three values

for August I have {'August':31, 'August':13, 'August':21} what I would like to have is the max Value 'August':31 or better {'August': [13,21,31]}八月我有 {'August':31, 'August':13, 'August':21} 我想要的是最大值 'August':31 或更好的 {'August': [13,21, 31]}

I know that in Python Dict only accepts one identical key我知道在 Python Dict 中只接受一个相同的键

not allowed to use packages/libraries不允许使用包/库

can i use class?我可以使用类吗?

thanks谢谢

what I would like to have is the max Value我想要的是最大值

to handle those types of collisions you would first check to see if the key already exists要处理这些类型的冲突,您首先要检查密钥是否已经存在

if month in myCalender.keys():

if it does exist you would redeclare it with the max of both the inputs如果它确实存在,您将使用两个输入的最大值重新声明它

myCalender[month] = max(myCalender[month], day_month[month] )

or better {'August': [13,21,31]}或更好的 {'August': [13,21,31]}

to do this you would do the same as above to check whether or the key already exists为此,您将执行与上述相同的操作以检查密钥是否已存在

if it does you would then append the new value to the list inside the dict如果是,则将新值附加到 dict 内的列表中

myCalender[month] = list(myCalender[month]).append(day_calender[month])

Here is one way of representing your data so that it is legal Python code that preserves all of the original data:这是表示数据的一种方式,因此它是保留所有原始数据的合法 Python 代码:

myCalendar = [('April', 30), ('July',10), ('May',20), ('February',29), ('August', 31), ( 'August', 13), ('August', 21)]

If you do that, you can then produce the structure you want with the following code:如果这样做,则可以使用以下代码生成所需的结构:

myCalendar = [('April', 30), ('July',10), ('May',20), ('February',29), ('August', 31), ( 'August', 13), ('August', 21)]

myIndex = {}
for k, v in myCalendar:
    if k not in myIndex:
        myIndex[k] = []
    myIndex[k].append(v)

print(myIndex)

Result:结果:

{'April': [30], 'July': [10], 'May': [20], 'February': [29], 'August': [31, 13, 21]}

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

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