创建一个列表,然后将项用作字典中的值

2024-09-24 22:31:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用Python创建的带有循环的列表,我想把这个列表的每一项都赋值。听起来很简单,但我需要创建与mu列表中相同数量的字典。你知道吗

arr_temp = []
for i in range(random.randrange(1,len(findings_list))):
    rand_item = random.choice(findings_list)
    arr_temp.append(rand_item)
# ['Lymph nodes', 'Calcifications US']

完成此操作后,我需要创建两个键名为“name”且值为list item的字典, 所以在这种情况下,我想要

dict1 = {"name": 'Lymph nodes'}
dict2 = {"name": 'Calcifications US'}

另外,如果您可以建议任何有效的方法将字典数组添加到dict键,那么

...findings: [{"name": 'Lymph nodes'}, 
              {"name": 'Calcifications US'}]

我会非常感激的。谢谢!你知道吗


Tags: name列表字典randomitemtemplistnodes
3条回答
String = ""

for i in range(1, len(arr_temp) + 1):
    String += "dict" + str(i) + " = " + {/"name/": '" + str(arr_temp[i - 1]) + "'}\n'

exec(String)

我知道使用execeval是不受欢迎的,但我只是在回答这个问题。如果OP想用它,那是她的选择。你知道吗

my_list = ['Lymph nodes', 'Calcifications US']
[{'name': v} for v in my_list]
[{'name': 'Lymph nodes'}, {'name': 'Calcifications US'}]
{'findings': [{"name":x} for x in arr_tmp]}

相关问题 更多 >