Alice Jarmusch
Alice Jarmusch

Reputation: 477

Create a list and then use items as a values in the dictionary

I have a list created in Python with a loop, and I want to assign each item of this list as a value. Sounds easy, but I need to create exactly the same number of dictionaries as I have in mu list.

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']

After doing this, I need to create 2 dictionaries with key name of "name" and value of list item, so in this case I would like to have something like

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

Also, if you can suggest any efficient way to add an array of dictionaries to dict key, so it will look like

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

I will really appreciate it. Thanks!

Upvotes: 0

Views: 74

Answers (3)

Adi219
Adi219

Reputation: 4814

String = ""

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

exec(String)

I KNOW that it's frowned upon to use exec or eval, but I'm just answering the question. If OP wants to use it, it's her choice.

Upvotes: 0

Amit
Amit

Reputation: 20456

{'findings': [{"name":x} for x in arr_tmp]}

Upvotes: 2

Asterisk
Asterisk

Reputation: 3574

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

Upvotes: 2

Related Questions