辞書のチュートリアル

Patricia Arquette
Patricia Arquetteオリジナル
2025-01-24 04:12:10970ブラウズ

Dictionary Tutorial

#Task 1
players = {'virat':190, 'rohit':87, 'dhoni':95, 'bumrah':100, 'sachin':78, 'Rahul':160}
#Total Score
total_score = 0
for k, v in players.items():
    total_score = total_score + v
print(total_score)
print()

#Task 2
#Highest Scorer
highest = 0 
for k, v in players.items():
    if v > highest:
        highest = v
        high_k = k
print(high_k,highest)
print()


#Task 3: 
#Frequency of each letter in a given word: 
name = "delllaptop"
d = {}
for letter in name:
    d[letter] = d.get(letter,0) + 1
print(d)
print()

#Task 4 :
#Frequency of each word in a given sentence
#str = 'a rose is a rose is a rose'
str = 'Cat is a pet , Cat is on the table and Cat is sleeping'
i = 0 
previous_space = 0
dict = {}
while i < len(str):
    if str[i] == ' ':
        dict[str[previous_space:i]] = dict.get(str[previous_space:i],0)+1
        previous_space = i+1 
    i+=1
else:
    dict[str[previous_space:len(str)]] = dict.get(str[previous_space:len(str)],0)+1
print(dict)
print()


#Task 5 :
#Sort based on values: 
players = {'virat':190, 'rohit':87, 'dhoni':95, 'bumrah': 80, 'hardik':66, 'pant':34, 'sachin':98}
sorted_dict ={}
lowest = list(players.values())[0]
lowest_key = list(players.keys())[0]
i=0
length = int(len(players))
while i<length:
    for k, v in players.items():
        if v < lowest:
            lowest = v
            lowest_key = k
    sorted_dict[lowest_key] = lowest
    players = {k:v for k, v in players.items() if k!= lowest_key}
    if players != {}:
        lowest = list(players.values())[0]
        lowest_key = list(players.keys())[0]
    i+=1
print(sorted_dict)










以上が辞書のチュートリアルの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。