如何从字典值中删除逗号?

时间:2021-06-05 03:53:55

标签: python dictionary comma

我正在尝试创建学校词典。

这是我使用的代码:

list_of_schools=["Cornell","UChicago","Johns Hopkins","Harvard","SNU","UBaltimore"]
y=len(list_of_schools)
list_of_indexes=list(range(1,(y+1)))


dictionary_of_schools={number:school.split() for number, school in zip(list_of_indexes,list_of_schools)}
print(dictionary_of_schools)

我得到的结果是这样的:

{1: ['Cornell'], 2: ['UChicago'], 3: ['Johns', 'Hopkins'], 4: ['Harvard'], 5: ['SNU'], 6: ['UBaltimore']}

我想要的结果是这个

{1: ['Cornell'], 2: ['UChicago'], **3: ['Johns Hopkins']**, 4: ['Harvard'], 5: ['SNU'], 6: ['UBaltimore']}

我尝试使用 split 函数和 strip 函数,但无济于事。请指教!

谢谢~

2 个答案:

答案 0 :(得分:3)

您可以将字典推导式与 enumerate 和 * 运算符一起使用。

list_of_schools=["Cornell","UChicago","Johns Hopkins","Harvard","SNU","UBaltimore"]

res = {idx:i for idx, *i in enumerate(list_of_schools, 1)}

print(res)

输出

{1: ['Cornell'], 2: ['UChicago'], 3: ['Johns Hopkins'], 4: ['Harvard'], 5: ['SNU'], 6: ['UBaltimore']}

答案 1 :(得分:1)

我的意思是,如果您要使用 .split(),它将拆分字符串 。因此,您可以轻松地将 school 包装在 [] 中。

dictionary_of_schools={number:[school] for number, school in zip(list_of_indexes,list_of_schools)}

输出

{1: ['Cornell'], 2: ['UChicago'], 3: ['Johns Hopkins'], 4: ['Harvard'], 5: ['SNU'], 6: ['UBaltimore']}

还可以使用 enumerate,它绝对可以帮助您。

dictEx = {count:[school] for count,school in enumerate(list_of_schools,1)}