[英]defaultdict of list
>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(<class 'list'>, {'key': [1]})
我在我的 django 應用程序中使用 defaultdict 作為列表,但想在沒有 <{}[] 的情況下獲取 output 是否可能?
首先,您必須創建數據。 其次,您獲得數據的密鑰。 最后,您必須循環每個鍵。
您可以使用以下不言自明的代碼:
import collections
info=collections.defaultdict(list,{'List of tubes': ['2324', '98', '7654'], 'List of auto:': [147, 10048, 1009, 10050, 10, 1647, 10648, 649, 1005]})
#print(info)
keys=info.keys()
for key in keys: # loop for each key
print(f'\'{key}\': ',end='')
tmp=info[key]
for i,data in enumerate(tmp):
if isinstance(data, str): # for the string type
if i!=len(tmp)-1:
print('\'%s\', '%(data),end='')
else:
print('\'%s\''%(data),end='')
else: # for the int type
if i!=len(tmp)-1:
print('%d, '%(data),end='')
else:
print('%d'%(data),end='')
print()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.