数据类型转化

列表 与 字典

一、dict & list

1、字典转化为列表

遍历索引,遍历元素

lst2 = {'perms': [{'db': 'merchant', 'db_name': 'csprd', 'perms': 'QUERY'},
                  {'db': 'oversea', 'db_name': 'prd', 'perms': 'QUERY'},
                  {'db': 'bidding', 'db_name': 'pre', 'perms': 'QUERY'},
                  {'db': 'order', 'db_name': 'perf', 'perms': 'QUERY'}],
    'username': '夜铭',
    'role': ['USER'],
    'env': 'product'}
# 带参数1,取消默认索引从0开始
for p, s in enumerate(lst2, 1):
    # p 是索引号
    # s 是字典的key
    # lst2[s] 是字典的value
    print([s, lst2[s]])

out:

['perms', [{'db': 'merchant', 'db_name': 'csprd', 'perms': 'QUERY'}, {'db': 'oversea', 'db_name': 'prd', 'perms': 'QUERY'}, {'db': 'bidding', 'db_name': 'pre', 'perms': 'QUERY'}, {'db': 'order', 'db_name': 'perf', 'perms': 'QUERY'}]]
['username', '夜铭']
['role', ['USER']]
['env', 'product']

2、多个列表合并并转化为字典

dbs = ['merchant', 'order', 'bidding', 'payment', 'marketing']
owns = ['lucy', 'mike', 'john', 'sihye', 'jack']
sexs = ['g', 'b', 'b', 'b', 'g']

grou = dict()
for db, own, sex in zip(dbs, owns, sexs):
    grou.setdefault(db, {}).update({own: sex})
pprint(grou)

grou out:

{'bidding': {'john': 'b'},
 'marketing': {'jack': 'g'},
 'merchant': {'lucy': 'g'},
 'order': {'mike': 'b'},
 'payment': {'sihye': 'b'}}
posted @ 2020-07-06 15:42  sihte  阅读(118)  评论(0编辑  收藏  举报