【发布时间】:2022-01-02 23:34:22
【问题描述】:
我想替换选项 label 和 value input text,我可以访问它们并更新它们,但它会更新所有值而不仅仅是一个 标签或输入文本,但所有索引。
response=[ {'arr': [{'title': 'Wählen Sie das passende Rechtsgebiet:',
'options': [{'label': 'Monday 1:00 pm', 'value': {'input': {'text': 'Monday 1:00 pm'}}},
{'label': 'Monday 1:00 pm', 'value': {'input': {'text': 'Monday 1:00 pm'}}}],
'description': '', 'response_type': 'option'}]}]
我的代码更新字典值它可以工作,但它用相同的值更新两个索引:
response['arr'][0]['options'][0].update({'label': "Contract Law"})
response['arr'][0]['options'][0]['value']['input'].update({'text': "Contract Law"})
response['arr'][0]['options'][1].update({'label': "Sales law"})
response['arr'][0]['options'][1]['value']['input'].update({'text': ""Sales law""})
完整代码:
import numpy as np
list_foci=["Erbschaftssteuerrecht","Erbrecht"]
list_size=len(list_foci)
dynamic_list= [
{
"title": "What time do you want your appointment?",
"options": [
{
"label": "Monday 1:00 pm",
"value": {
"input": {
"text": "Monday 1:00 pm"
}
}
}
],
"description": "",
"response_type": "option"
}
]
#for creating new values from the first index options e.g. label,value etc....
updated=list(np.repeat(dynamic_list[0]['options'], list_size))
response={
"arr": [
{
"title": "Wählen Sie das passende Rechtsgebiet:",
"options": updated,
"description": "",
"response_type": "option"
}
]
}
response['arr'][0]['options'][0]['label']= "Contract Law"
response['arr'][0]['options'][0]['value']['input']['text'] = "Contract Law"
response['arr'][0]['options'][1]['label']= "Sales Law"
response['arr'][0]['options'][1]['value']['input']['text'] = "Sales Law"
print(response)
【问题讨论】:
-
无法重现:您的代码在我的 python 3.6.9 上正常工作。您使用的是哪个版本?我得到了这个输出:
{'arr': [{'title': 'Wählen Sie das passende Rechtsgebiet:', 'options': [{'label': 'Contract Law', 'value': {'input': {'text': 'Contract Law'}}}, {'label': 'Sales law', 'value': {'input': {'text': 'Sales law'}}}], 'description': '', 'response_type': 'option'}]} -
np.repeat的使用看起来很奇怪。它不会产生新的optionsdicts。它只是增加了对原始的引用。我认为numpy在这里没有任何用处。 -
@yondaime 我正在使用 Python 3.8.10
-
@hpaulj 如果它正在创建引用,我该如何做出新的选择
-
如果您想要一个不同对象的列表,请使用列表推导,在每次迭代时创建一个新对象或副本。这是基本的 Python。
标签: python list numpy dictionary ibm-watson