[Python]Using dictionaries and lists

1. List nested dictionary
Dictionary as an element in the list:

Student information list: [Student 1, Student 2,...]

Student Information Dictionary: {Name: Hobbies}

Hobby list: [Hobby 1, Hobby 2, Hobby 3]

The overall data structure is [{Name of student 1: [Hobby 1, Hobby 2, Hobby 3]}, {Name of student 2: [Hobby 1, Hobby 2, Hobby 3]},...]

student_info_dict = {}
student_info_list = []
hobby_list = []
while True:
    name = input("请输入学生姓名:")
    if name == " ":
        break
    else:
        for i in range(3):
            hobby = input("请输入第{}个爱好:".format(i+1))
            if hobby == " ":
                break
            else:
                hobby_list.append(hobby)
    student_info_dict = {name: hobby_list[:]}
    hobby_list.clear()
    student_info_list.append(student_info_dict)

print(student_info_list)
for i in student_info_list:
    print(i)

2. Dictionary application exercises:

Determine the number of occurrences of each character in the string, and use the non-repeatability of the key in the dictionary to determine whether the character has appeared. The character is used as the key and the number of occurrences is used as the value.

# abcdefce

str01 = "abcdefce"
str01_list = list(str01)
str_dict = {}
str_dict[str01_list[0]] = 1

for i in range(1,len(str01_list)):
    if str01_list[i] in str_dict.keys():
        str_dict[str01_list[i]] += 1
    else:
        str_dict[str01_list[i]] = 1

for key,value in str_dict.items():
    print(key,value)


#output 
a 1
b 1
c 2
d 1
e 2
f 1

Guess you like

Origin blog.csdn.net/x1987200567/article/details/109169935