一个dict和一个列表:转换和何时使用哪个 [英] A dict and a list of dicts: conversion and when to use which

查看:69
本文介绍了一个dict和一个列表:转换和何时使用哪个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 我们如何将具有元组(键,值)的dict转换为
    的列表,每个dict都带有key和value? / p>

    例如:

      dic = {'Tim':3, 凯特:2} 

    成为

      lst = [{'Name':'Tim','Age':3},{'Name':'Kate','Age':2}] 


  2. 使用每个
    表示法有哪些优点和缺点? (例如,考虑我们可以想到的
    并自然适用于它们的操作)。谢谢。


解决方案

您可以使用列表解析:

 >>> dic = {'Tim':3,'Kate':2} 
>>> [{'Name':i,'Age':j} for i,j in dic.items()]
[{'Age':3,'Name':'Tim'},{'Age' :2,'Name':'Kate'}]

相反:

 >>> l = [{'Name':i,'Age':j} for i,j in dic.items()] 
>>>>对于我的l))中的((i.values()[:: - 1])$ ​​b $ b {'Tim':3,'Kate':2}
pre>

  1. How can we convert a dict with tuples (key, value), into a list of dicts, each dict with keys "key" and "value"?

    For example:

    dic={'Tim':3, 'Kate':2}
    

    becomes

    lst = [{'Name':'Tim', 'Age':3}, {'Name':'Kate', 'Age':2}]
    

  2. What are some advantages and disadvantages of using each representation? (e.g. consider the operations which we can think of and apply to them naturally). Thanks.

解决方案

You can use a list comprehension :

>>> dic={'Tim':3, 'Kate':2}
>>> [{'Name':i, 'Age':j} for i,j in dic.items()]
[{'Age': 3, 'Name': 'Tim'}, {'Age': 2, 'Name': 'Kate'}]

and for opposite :

>>> l=[{'Name':i, 'Age':j} for i,j in dic.items()]
>>> dict((i.values()[::-1] for i in l))
{'Tim': 3, 'Kate': 2}

这篇关于一个dict和一个列表:转换和何时使用哪个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆