Reputation: 2495
I have a dictionary like the following:
{'invoice_date': '2021-02-12T15:48:52+05:30',
'no_of_bill_files': '3',
'amount': '12', 'gst': '12',
'bill0': 123, 'bill1': 456, 'bill2': 789, 'owner': 2}
I want to create a list by name bill
which would contain data like this:
bill = [{'document':123},{'document':456},{'document':789}]
the number of dictionary depends upon the number of 'no_of_bill_files'
in the above dictionary
How do I do that?
Upvotes: 0
Views: 36
Reputation: 15872
Let's say you first dict name is cond
:
>>> cond = {'invoice_date': '2021-02-12T15:48:52+05:30',
'no_of_bill_files': '3',
'amount': '12', 'gst': '12',
'bill0': 123, 'bill1': 456, 'bill2': 789, 'owner': 2}
>>> bill = [{'document': cond[f'bill{i}']} for i in range(int(cond['no_of_bill_files']))]
>>> bill
[{'document': 123}, {'document': 456}, {'document': 789}]
Here we use a list comprehension
, where the number of iteration is equal to cond['no_of_bill_files']
.
>>> cond['no_of_bill_files']
'3'
# Now as it is in string, in order to use it in range
# we will need to convert it to int
Now for range(3)
, the values after all the iteration will be 0, 1 and 2
, we add that to bill
using f-string
and get the value from cond
dict.
>>> for i in range(3):
print(f'bill{i}')
bill0
bill1
bill2
Upvotes: 1