繁体   English   中英

列表的默认值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM