簡體   English   中英

python - 字典中有多個相同的鍵

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

這是我的代碼

#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]))

這些是輸出

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

八月我有 {'August':31, 'August':13, 'August':21} 我想要的是最大值 'August':31 或更好的 {'August': [13,21, 31]}

我知道在 Python Dict 中只接受一個相同的鍵

不允許使用包/庫

我可以使用類嗎?

謝謝

我想要的是最大值

要處理這些類型的沖突,您首先要檢查密鑰是否已經存在

if month in myCalender.keys():

如果它確實存在,您將使用兩個輸入的最大值重新聲明它

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

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

為此,您將執行與上述相同的操作以檢查密鑰是否已存在

如果是,則將新值附加到 dict 內的列表中

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

這是表示數據的一種方式,因此它是保留所有原始數據的合法 Python 代碼:

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

如果這樣做,則可以使用以下代碼生成所需的結構:

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)

結果:

{'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