python-3.x - 具有来自字符串字符的不同键的字典列表
问题描述
这些是我的输入
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}
谢谢
解决方案
这只会为相同的数据创建一个新名称:
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
推荐阅读
- python - Python 不知道停止
- angular - (Angular) 将 *ngFor "i" 值设置为 (data.id)
- elixir - 如何在 Elixir 中将宏列表转换为字符串
- html - 使背景图像适合而不切断/拉伸图像
- express - 如何在服务器上的两个“app.post”方法之间传递数据?(节点/快递)
- xamarin.forms - WhenActivated 在 App.OnSleep 之后调用,而不是在 App.Resume 之后调用
- vhdl - 测试台错误说我没有数组时
- rest - 公共 API 架构
- html - 如何将文本推送到 flex 的右侧
元素
- javascript - 无法在嵌入式画面中单击() div 元素