[英]create a dictionary from variables of another dictionary
我有一本像下面這樣的字典:
{'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}]
字典的數量取決於上述字典中'no_of_bill_files'
的數量
我怎么做?
假設您的第一個字典名稱是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
dict 中獲取值。
>>> for i in range(3):
print(f'bill{i}')
bill0
bill1
bill2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.