英文:
How to fix dictionary error with same keys having different values
问题
I have a text file with lines having two columns (separated by a Tab). I want to open this file and have as output a dictionary, store the 1st column as keys, then the 2nd column as values. But I am difficulty handling keys that have different values (like Camiguin
below):
Sandingan Loon, Bohol Pangangan Calape, Bohol Limasawa Limasawa, Southern Leyte Catalat San Vicente, Palawan Camiguin Catarman, Camiguin Camiguin Guinsiliban, Camiguin Camiguin Mahinog, Camiguin Camiguin Mambajao, Camiguin Camiguin Sagay, Camiguin Rasa Narra, Palawan
The code I used is:
filesDir = "C:\Users\user\Desktop"
fhand = open(filesDir+"\input.txt")
fout = open(filesDir+"output.txt","w")
d = dict()
for line in fhand:
x = line.rstrip("\n")
x = x.split("\t")
if x[0] not in d:
d[x[0]] = x[1]
else:
d[x[0]] += x[1]
continue
print(d)
The result I am getting is this (note the result for Camiguin
which simply concatenated the values together. I probably would need to use a list, but I cannot figure how to):
{'Limasawa': 'Limasawa, Southern Leyte', 'Rasa': 'Narra, Palawan', 'Catalat': 'San Vicente, Palawan', 'Camiguin': 'Catarman, CamiguinGuinsiliban, CamiguinMahinog, CamiguinMambajao, CamiguinSagay, Camiguin', 'Pangangan': 'Calape, Bohol', 'Sandingan': 'Loon, Bohol'}
EDIT: My desired output should be something like this:
{'Limasawa': 'Limasawa, Southern Leyte', 'Rasa': 'Narra, Palawan', 'Catalat': 'San Vicente, Palawan', 'Camiguin': ['Catarman, Camiguin','Guinsiliban, Camiguin','Mahinog, Camiguin','Mambajao, Camiguin','Sagay, Camiguin'], 'Pangangan': 'Calape, Bohol', 'Sandingan': 'Loon, Bohol'}
英文:
I have a text file with lines having two columns (separated by a Tab). I want to open this file and have as output a dictionary, store the 1st column as keys, then the 2nd column as values. But I am difficulty handling keys that have different values (like Camiguin
below):
<pre>
Sandingan Loon, Bohol
Pangangan Calape, Bohol
Limasawa Limasawa, Southern Leyte
Catalat San Vicente, Palawan
Camiguin Catarman, Camiguin
Camiguin Guinsiliban, Camiguin
Camiguin Mahinog, Camiguin
Camiguin Mambajao, Camiguin
Camiguin Sagay, Camiguin
Rasa Narra, Palawan
</pre>
The code I used is:
filesDir = "C:\Users\user\Desktop"
fhand = open(filesDir+"\input.txt")
fout = open(filesDir+"output.txt","w")
d = dict()
for line in fhand:
x = line.rstrip("\n")
x = x.split("\t")
if x[0] not in d:
d[x[0]] = x[1]
else:
d[x[0]] += x[1]
continue
print(d)
The result I am getting is this (note the result for Camiguin
which simply concatenated the values together. I probably would need to use a list, but I cannot figure how to):
{'Limasawa': 'Limasawa, Southern Leyte', 'Rasa': 'Narra, Palawan', 'Catalat': 'San Vicente, Palawan', 'Camiguin': 'Catarman, CamiguinGuinsiliban, CamiguinMahinog, CamiguinMambajao, CamiguinSagay, Camiguin', 'Pangangan': 'Calape, Bohol', 'Sandingan': 'Loon, Bohol'}
EDIT: My desired output should be something like this:
{'Limasawa': 'Limasawa, Southern Leyte', 'Rasa': 'Narra, Palawan', 'Catalat': 'San Vicente, Palawan', 'Camiguin': ['Catarman, Camiguin','Guinsiliban, Camiguin','Mahinog, Camiguin','Mambajao, Camiguin','Sagay, Camiguin'], 'Pangangan': 'Calape, Bohol', 'Sandingan': 'Loon, Bohol'}
答案1
得分: 2
使用defaultdict而不是使用字典,这样你可以始终添加:
from collections import defaultdict
d = defaultdict(list)
for line in fhand:
x = line.rstrip("\n")
x = x.split("\t")
d[x[0]].append(x[1])
print(d)
英文:
Instead of using a dictionary, use a defaultdict, then you can always append
from collections import defaultdict
d = defaultdict(list)
for line in fhand:
x = line.rstrip("\n")
x = x.split("\t")
d[x[0]].append(x[1])
print(d)
答案2
得分: 2
Using dict.setdefault
Ex:
res = {}
with open(filename) as infile:
for line in infile:
key, value = line.strip().split("\t") # 获取行中的键值对
res.setdefault(key, []).append(value) # 使用列表追加值
print(res)
Output:
{'Camiguin': ['Catarman, Camiguin',
'Guinsiliban, Camiguin',
'Mahinog, Camiguin',
'Mambajao, Camiguin',
'Sagay, Camiguin'],
'Catalat San': ['Vicente, Palawan'],
'Limasawa': ['Limasawa, Southern Leyte'],
'Pangangan': ['Calape, Bohol'],
'Rasa': ['Narra, Palawan'],
'Sandingan': ['Loon, Bohol']}
英文:
Using dict.setdefault
Ex:
res = {}
with open(filename) as infile:
for line in infile:
key, value = line.strip().split("\t") #Get key-value from line
res.setdefault(key, []).append(value) #Use list to append values.
print(res)
Output:
{'Camiguin': ['Catarman, Camiguin',
'Guinsiliban, Camiguin',
'Mahinog, Camiguin',
'Mambajao, Camiguin',
'Sagay, Camiguin'],
'Catalat San': ['Vicente, Palawan'],
'Limasawa': ['Limasawa, Southern Leyte'],
'Pangangan': ['Calape, Bohol'],
'Rasa': ['Narra, Palawan'],
'Sandingan': ['Loon, Bohol']}
答案3
得分: 0
在你的 else 循环下,你可以检查分配给该键的值的类型。如果类型是字符串,将其替换为包含当前字符串和新值的列表。如果值已经是一个列表,则将新值附加到它。
else:
if type(d[x]) == 'str':
d[x] = [d[x], x[1]]
elif type(d[x]) == 'list':
d[x].append(x[1])
英文:
Under your else loop, you can check the type of the value assigned to that key. If the type is a string, replace it with a list containing the current string and the new value. If the value is already a list, append the new value to it.
else:
if type(d[x]) == 'str':
d[x] = [d[x], x[1]]
elif type(d[x] == 'list'):
d[x].append(x[1])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论