这是我的代码:
with open('kamus_singkatan.csv', 'r') as file:
data = file.read().rstrip()
print(data)
arr = data.split('\n')
arr
代码:
arr = [a.split(';') for a in arr]
arr
这是我出错的时候:
cor = {kv[0].strip(): kv[1].strip() for kv in arr}
cor
您可以遍历列表并检查每个子列表的长度(=2 和 !=2(特殊情况)),然后对每种情况执行您想要的操作
lst = [["a ", "b "], ["c ", "d "], ["e ", "f"], [" g"]]
my_dict = {}
for sublst in lst:
if len(sublst) == 2: # Normal case, there are 2 values in a list
key = sublst[0].strip()
value = sublst[1].strip()
my_dict[key] = value
elif len(sublst) != 2: # Special case, for example 1 value in a list
key = sublst[0].strip() # Set the value in the list be the key of the dict
my_dict[key] = "special_case" # The value of the dict is a character you choose
print(my_dict) # {'a': 'b', 'c': 'd', 'e': 'f', 'g': 'special_case'}