python—最终目标是创建一个字典,其中重复的名称组合成一个键,其值是多个元素

62o28rlo  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(351)

我有一个经过for循环的列表,以便将每个元素分别作为字符串生成。接下来,我创建了一个变量来拆分这些字符串,以获得key=pairs(生成多个列表)。基本上,这些列表只有两个元素,[0]用作键,[1]用作值。如何将这些列表转换为字典,其中重复的键组合在一起,它们的[1]是它们的值?我是新手,所以请不要使用像def这样的高级代码。想想基本的。

lst = ["help-please" , "desperate-fix", "help-today", "desperate-need"]
for i in lst:
    a = i
    b = a.split("-")
    c = b[0]  #keys
    d = b[1]  #values
    e = {c:d} #how do I fix this to one key to many values? I believe this should be a loop to 
             facilitate many key:value pairs

我的ulitmate目标:

e = {"help": ["please", "today"], "desperate": ["fix", "need"]
w8ntj3qf

w8ntj3qf1#

lst = ["help-please" , "desperate-fix", "help-today", "desperate-need"]
ret_dict = {}
for i in lst:
    a = i
    b = a.split("-")
    c = b[0]  #keys
    d = b[1]  #values
    if c in ret_dict.keys():
        ret_dict[c].append(d)  # If key already exists then append to list
    else:
        ret_dict[c] = [d]      # else make new list and add d as the first element

print(ret_dict)

相关问题