我有一本像下面这样的字典:
<pong>
我想按名称 {'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
字典的数量取决于上面字典中bill = [{'document':123},{'document':456},{'document':789}]
的数量
我该怎么做?
答案 0 :(得分:1)
假设您的第一个 dict 名称是 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}]
这里我们使用list comprehension
,其中迭代次数等于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
现在对于 range(3)
,所有迭代后的值将是 0, 1 and 2
,我们使用 f-string
将其添加到 bill
并从 cond
获取值字典。
>>> for i in range(3):
print(f'bill{i}')
bill0
bill1
bill2