首页 > 解决方案 > 具有来自字符串字符的不同键的字典列表

问题描述

这些是我的输入

hand = {'*': 1, 'v': 2, 'n': 1, 'i': 1, 'l': 2}
string = 'abc'

我需要用字符串中的每个字符替换 '*' 并将新字典附加到列表中。我需要的输出是这样的:

[{'v': 2, 'n': 1, 'i': 1, 'l': 2, 'a': 1}, {'v': 2, 'n': 1, 'i': 1, 'l': 2, 'b': 1}, {'v': 2, 'n': 1, 'i': 1, 'l': 2, 'c': 1}]

这就是我所做的,它不起作用。我尝试了几种不同的方法,但没有成功。

del hand['*']
for x in string:
    item = {x: 1}
    newHand = hand
    newHand.update(item)
    print(newHand)
    list.append(newHand)
    newHand.pop(x)
print(list)

下面的输出是我试图避免的:

{'v': 2, 'n': 1, 'i': 1, 'l': 2, 'a': 1, 'b': 1, 'c': 1}

谢谢

标签: python-3.xdictionary

解决方案


这只会为相同的数据创建一个新名称:

newHand = hand

你总是在修改同一个字典。您将引用存储到您的list(顺便说一句。不要list用作变量名 - 您隐藏内置的list())。如果你打印id()你的列表内容,你会看到它们都是一样的:

print( id(x) for x in list) # try that to see its the same object trice

您需要复制数据来创建三个不同的字典。

我选择dict从你那里更新 1-elem 并用 popping 后string的剩余部分更新它们:hand'*'

hand = {'*': 1, 'v': 2, 'n': 1, 'i': 1, 'l': 2}

s = hand.pop("*")  # removes * and stores the calue
t = "abc"

# create a list of new dicts wich 1 elem each
l = [ {c:s} for c in t]

# update all inner dicts
for d in l:
    d.update(hand) # add what is in hand left

print(l)

输出:

[{'a': 1, 'i': 1, 'v': 2, 'l': 2, 'n': 1}, 
 {'i': 1, 'b': 1, 'v': 2, 'l': 2, 'n': 1}, 
 {'i': 1, 'c': 1, 'v': 2, 'l': 2, 'n': 1}]

您可以在此处找到有关可变副本的更多信息:如何克隆或复制列表?


要同时更新现有密钥:

for d in l:
    for thing in hand:
        d.setdefault(thing,0)       # create key if not exists and set to 0
        d[thing] += hand[thing]     # add hands value on top

推荐阅读