【问题标题】:Turning list into dictionary where list value is dict key and value将列表转换为字典,其中列表值为字典键和值
【发布时间】:2020-11-27 20:43:59
【问题描述】:

我有一个包含长字符串的列表,一个数字,然后是一个“句子”,比如说。我想知道是否有办法把它变成字典,数字就是值

mylist = ['8 red cars', '3 blue cars', '11 black cars']

这是我的清单,我希望字典是:

{
 'red cars': 8
 'blue cars': 3
 'black cars': 11
}

【问题讨论】:

  • 您是否尝试为此编写任何代码?例如,您认为流程中的逻辑步骤是什么?每一步都写代码吗?
  • @NikolaosChatzis 有趣...这个问题是完全相同的问题...由同一个人在大约一个小时前提出...并将其作为副本关闭。
  • 经过进一步调查,看起来实际上 OP 从前一个问题中编辑了该问题,使其成为这个问题......然后重新问它......很奇怪。哦,请不要那样做。我回滚了对另一个问题的编辑。
  • 嗨,对不起,我原来的问题是不同的,因为有人发现了一个类似的问题,所以它被关闭了,所以我只是想我可以将它编辑为一个新问题!道歉

标签: python list dictionary


【解决方案1】:

我确信有更好的方法,但下面的代码适用于您的示例。

mylist = ['8 red cars', '3 blue cars', '11 black cars']
car_dict = {}

for item in mylist:
    number = [int(s) for s in item.split() if s.isdigit()][0]
    words = [str(s) for s in item.split() if s.isalpha()]
    car_dict[number] = ' '.join(words)
    
print(car_dict)

【讨论】:

  • 谢谢,但我将列表扩展为:mylist = ['8 辆红色汽车','3 辆蓝色汽车','11 辆黑色汽车','1 辆黄色汽车','1 辆银色汽车' , '22 blue vans', '11 green cars', '11 black vans', '4 white cars'],但输出只有:{8: 'redcars', 3: 'bluecars', 11: 'blackvans' , 1: 'silvercar', 22: 'bluevans', 4: 'whitecars'}
  • 这是由于 python 中字典的性质造成的。所有键都必须是唯一的。由于编号 11 出现两次,第一个值将被第二个值覆盖。如何处理这取决于您自己,但字典中不能有 2 个相同的键。例如,您可以将值保存到 list。所以{11: ['black vans', 'black cars`]}等等
  • 啊,当然可以?在那种情况下,如果我将数字设为值并将“红色汽车”(例如)作为键,它会起作用吗?
  • 是的,如果对汽车的描述都是独一无二的,那肯定可以工作。因此,只需使用 car_dict[' '.join(words)] = number 而不是您现在拥有的那一行。
【解决方案2】:

所有以前的方法都是完全有效的,但我要投入我的两分钱:

d = {}
for x in ['8 red cars', '3 blue cars', '11 black cars']:
    [k, v] = x.split(' ', 1) # ['8', 'red cars']
    d[int(k)] = v

print(d) # {8: 'red cars', 3: 'blue cars', 11: 'black cars'}

更新

显然你已经更新了你的问题,所以这里是相应的答案:

d = {}
for x in ['8 red cars', '3 blue cars', '11 black cars']:
    [k, v] = x.split(' ', 1) # ['8', 'red cars']
    d[v] = int(k)

print(d) # {'red cars': 8, 'blue cars': 3, 'black cars': 11}

【讨论】:

    【解决方案3】:

    [编辑]:问题已编辑。 (反转KEY、VALUE的位置)

    mylist = ['8 red cars', '3 blue cars', '11 black cars', '1 yellow car', '1 silver car', '22 blue vans', '11 green cars', '11 black vans', '4 white cars']
    
    split_list=[i.split(' ', 1) for i in mylist]
    
    flat_list = []
    for sublist in split_list:
        flat_list.extend(sublist)
    
    dict= {flat_list[i+1]: int(flat_list[i]) for i in range(0, len(flat_list), 2)}
    print(dict)
    

    [结果]:

    dict={
    'red cars': 8,
    'blue cars': 3, 
    'black cars': 11, 
    'yellow car': 1, 
    'silver car': 1, 
    'blue vans': 22, 
    'green cars': 11, 
    'black vans': 11, 
    'white cars': 4
    }
    

    【讨论】:

    • 谢谢,我将如何编辑这个数字现在是值而不是键?
    • 我已经编辑了答案,使用 int(flat_list[i]) 将数字从字符串值转换为数字键
    • 还是先打印数字?
    • 感谢@Dsmith97,现在我编辑代码,数字为VALUE,字符串为KEY。
    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2020-09-04
    相关资源
    最近更新 更多