如何将列表项合并到字典中,其中某些列表项具有相同的键?
How to combine list items into a dictionary where some list items have the same key?
这是我正在使用的文件,名为 file1.txt
20
Gunsmoke
30
The Simpsons
10
Will & Grace
14
Dallas
20
Law & Order
12
Murder, She Wrote
到目前为止,这是我的代码:
file = open('file1.txt')
lines = file.readlines()
print(lines)
new_list=[]
for i in lines:
new = i.strip()
new_list.append(new)
print(new_list)
new_dict = {}
for i in range(0,len(new_list),2):
new_dict[new_list[i]]=new_list[i+1]
if i in new_dict:
i[key] = i.values()
new_dict = dict(sorted(new_dict.items()))
print(new_dict)
file_2 = open('output_keys.txt', 'w')
for x, y in new_dict.items():
print(x, y)
file_2.write(x + ': ')
file_2.write(y)
file_2.write('\n')
file_2.close()
file_3 = open('output_titles.txt', 'w')
new_list2 = []
for x, y in new_dict.items():
new_list2.append(y)
new_list2.sort()
print(new_list2)
print(new_list2)
for i in new_list2:
file_3.write(i)
file_3.write('\n')
print(i)
file_3.close()
说明状态:
Write a program that first reads in the name of an input file and then reads the input file using the file.readlines()
method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since multiple shows could have the same number of seasons).
Sort the dictionary by key (least to greatest) and output the results to a file named output_keys.txt
. Separate multiple TV shows associated with the same key with a semicolon (;
), ordering by appearance in the input file. Next, sort the dictionary by values (alphabetical order), and output the results to a file named output_titles.txt
.
所以我在处理 2 个部分时遇到了问题:
首先是“用分号 (;) 分隔与同一键关联的多个电视节目”。
到目前为止我写的只是替换字典中的新条目。
for i in range(0,len(new_list),2):
new_dict[new_list[i]]=new_list[i+1]
if i in new_dict:
i[key] = i.values()
第二部分是在 Zybooks 程序中,它似乎每次迭代时都会添加到 output_keys.txt
和 output_title.txt
上。但是我的代码好像没有添加到output_keys和output_title。例如,如果在我 运行 file1.txt
之后我尝试 运行 file2.txt
,它会替换 output_keys
和 output_title
而不是添加到它。
正如我所见,您尝试检查字典中是否已经存在键,但似乎那里有错误,如果字典中存在,您应该检查值而不是索引,并且在放入之前必须检查字典,如果它存在,您可以通过添加更新当前值;结束当前值
for i in range(0,len(new_list),2):
if not new_list[i] in new_edict.keys():
new_edict[new_list[i]] = new_list[i+1]
else:
Update it here… like
new_list[new_list[i]] = new_list[new_list[i]] +";"+ new_list[i+1]
尝试将问题分解成更小的问题 sub-problems。现在,您似乎正试图一次解决所有问题。例如,我建议您省略文件输入和输出,而专注于程序的基本功能。设置完成后,您可以选择 I/O.
您首先需要创建一个字典,将季数作为键,将电视节目列表作为值。你几乎明白了;这是一个工作片段(我重命名了你的一些变量:拥有有意义的变量名总是一个好主意):
lines = file.readlines()
# formerly "new_list"
clean_lines = []
for line in lines:
line = line.strip()
clean_lines.append(line)
# formerly "new_dict"
seasons = {}
for i in range(0, len(clean_lines), 2):
season_num = int(clean_lines[i])
series = clean_lines[i+1]
# there are only two options: either
# the season_num is already in the dict...
if season_num in seasons:
# append to the existing entry
seasons[season_num].append(series)
# ...or it isn't
else:
# make a new entry with a list containing
# the series
seasons[season_num] = [series]
以下是如何使用 join
打印结果字典,其中电视节目以分号分隔。适应您的需求:
for season_num, series in seasons.items():
print(season_num, '; '.join(series))
输出:
20 Gunsmoke; Law & Order
30 The Simpsons
10 Will & Grace
14 Dallas
12 Murder, She Wrote
这是我正在使用的文件,名为 file1.txt
20
Gunsmoke
30
The Simpsons
10
Will & Grace
14
Dallas
20
Law & Order
12
Murder, She Wrote
到目前为止,这是我的代码:
file = open('file1.txt')
lines = file.readlines()
print(lines)
new_list=[]
for i in lines:
new = i.strip()
new_list.append(new)
print(new_list)
new_dict = {}
for i in range(0,len(new_list),2):
new_dict[new_list[i]]=new_list[i+1]
if i in new_dict:
i[key] = i.values()
new_dict = dict(sorted(new_dict.items()))
print(new_dict)
file_2 = open('output_keys.txt', 'w')
for x, y in new_dict.items():
print(x, y)
file_2.write(x + ': ')
file_2.write(y)
file_2.write('\n')
file_2.close()
file_3 = open('output_titles.txt', 'w')
new_list2 = []
for x, y in new_dict.items():
new_list2.append(y)
new_list2.sort()
print(new_list2)
print(new_list2)
for i in new_list2:
file_3.write(i)
file_3.write('\n')
print(i)
file_3.close()
说明状态:
Write a program that first reads in the name of an input file and then reads the input file using the
file.readlines()
method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since multiple shows could have the same number of seasons).Sort the dictionary by key (least to greatest) and output the results to a file named
output_keys.txt
. Separate multiple TV shows associated with the same key with a semicolon (;
), ordering by appearance in the input file. Next, sort the dictionary by values (alphabetical order), and output the results to a file namedoutput_titles.txt
.
所以我在处理 2 个部分时遇到了问题:
首先是“用分号 (;) 分隔与同一键关联的多个电视节目”。
到目前为止我写的只是替换字典中的新条目。
for i in range(0,len(new_list),2):
new_dict[new_list[i]]=new_list[i+1]
if i in new_dict:
i[key] = i.values()
第二部分是在 Zybooks 程序中,它似乎每次迭代时都会添加到 output_keys.txt
和 output_title.txt
上。但是我的代码好像没有添加到output_keys和output_title。例如,如果在我 运行 file1.txt
之后我尝试 运行 file2.txt
,它会替换 output_keys
和 output_title
而不是添加到它。
正如我所见,您尝试检查字典中是否已经存在键,但似乎那里有错误,如果字典中存在,您应该检查值而不是索引,并且在放入之前必须检查字典,如果它存在,您可以通过添加更新当前值;结束当前值
for i in range(0,len(new_list),2):
if not new_list[i] in new_edict.keys():
new_edict[new_list[i]] = new_list[i+1]
else:
Update it here… like
new_list[new_list[i]] = new_list[new_list[i]] +";"+ new_list[i+1]
尝试将问题分解成更小的问题 sub-problems。现在,您似乎正试图一次解决所有问题。例如,我建议您省略文件输入和输出,而专注于程序的基本功能。设置完成后,您可以选择 I/O.
您首先需要创建一个字典,将季数作为键,将电视节目列表作为值。你几乎明白了;这是一个工作片段(我重命名了你的一些变量:拥有有意义的变量名总是一个好主意):
lines = file.readlines()
# formerly "new_list"
clean_lines = []
for line in lines:
line = line.strip()
clean_lines.append(line)
# formerly "new_dict"
seasons = {}
for i in range(0, len(clean_lines), 2):
season_num = int(clean_lines[i])
series = clean_lines[i+1]
# there are only two options: either
# the season_num is already in the dict...
if season_num in seasons:
# append to the existing entry
seasons[season_num].append(series)
# ...or it isn't
else:
# make a new entry with a list containing
# the series
seasons[season_num] = [series]
以下是如何使用 join
打印结果字典,其中电视节目以分号分隔。适应您的需求:
for season_num, series in seasons.items():
print(season_num, '; '.join(series))
输出:
20 Gunsmoke; Law & Order
30 The Simpsons
10 Will & Grace
14 Dallas
12 Murder, She Wrote