Python更新对象中键中的值,来自列表
我是Python的初学者,也许我正在尝试做一些有点复杂的事情——我不知道。我正在绞尽脑汁思考如何做到这一点,以及正确的方法是什么,即正确的步骤 以下是我拥有的一本字典:Python更新对象中键中的值,来自列表,python,list,dictionary,Python,List,Dictionary,我是Python的初学者,也许我正在尝试做一些有点复杂的事情——我不知道。我正在绞尽脑汁思考如何做到这一点,以及正确的方法是什么,即正确的步骤 以下是我拥有的一本字典: [{'\id':'001', 'second_id':'0001', 'imp_url':"https://urlone.com", 'last_id':'00001'}, {'\id':'002', 'second_id':'0002', 'imp_url':"
[{'\id':'001',
'second_id':'0001',
'imp_url':"https://urlone.com",
'last_id':'00001'},
{'\id':'002',
'second_id':'0002',
'imp_url':"https://urltwo.com",
'last_id':'00002'}
]
以下是我的清单:
['imp_url', '["https://urltestx.com", "https://urltestxx.com"]']
所需的结果是一个更新的对象,该对象将更新键“imp_url”的值*,该键存在于列表(如上)中。像这样:
预期结果:
[{'\id':'001',
'second_id':'0001',
'imp_url':'["https://urltestx.com"]',
'last_id':'00001'},
{'\id':'002',
'second_id':'0002',
'imp_url':'["https://urltestxx.com"]',
'last_id':'00002'}
]
注*-括号和单引号保留在更新的预期结果中
我希望这是有道理的。我试着用dict
和zip
,然后掉进了一个frozensets
的兔子洞?我很确定我需要创建一个新的Dict
,但是我如何才能将一个对象从数组中的值更新到特定的键?我也尝试过使用.update()
,但似乎是用整数作为键,而不一定用单词作为键。我也不知道元组
有没有办法做到这一点
任何帮助都会非常有用!小迷失。。。谢谢大家-您的方向是正确的,您可以使用
ast.literal\u eval
将列表中的第二个元素变成实际的列表
seq = [{'\id':'001',
'second_id':'0001',
'imp_url':"https://urlone.com",
'last_id':'00001'},
{'\id':'002',
'second_id':'0002',
'imp_url':"https://urltwo.com",
'last_id':'00002'}
]
from ast import literal_eval
new_list = ['imp_url', '["https://urltestx.com", "https://urltestxx.com"]']
new_list[-1] = literal_eval(new_list[-1])
for d, url in zip(seq, new_list[-1]):
d[new_list[0]] = f'["{url}"]'
print(seq)
输出
[{'\\id': '001',
'second_id': '0001',
'imp_url': '["https://urltestx.com"]',
'last_id': '00001'},
{'\\id': '002',
'second_id': '0002',
'imp_url': '["https://urltestxx.com"]',
'last_id': '00002'}]
我使用的是python 3.9版,列表来自哪里?第二个元素看起来像JSON。我制作的列表,它有修改的目的。现在我需要获取内容并将其插入到一个特定的键中。您可以编辑您的问题来进一步解释吗?您有这样做的原因吗?
“[”https://urltestxx.com“]”
得到这一点没什么变化,外面用双引号,里面用单引号,换一种方式需要一些改变,第一种形式可以吗?如果不太麻烦的话,外面的单引号和里面的双引号会很好^ ^检查新的编辑@knowledgealways,如果它对你有帮助,你能投票并接受吗?