python 将字典的字典转换为字典列表

5us2dqdw  于 2023-01-12  发布在  Python
关注(0)|答案(5)|浏览(310)

我有一个字典的字典。有没有可能的方法把它转换成字典的列表?如果没有,那么如何应用filter()方法来过滤字典的字典中的数据?

{"0": {"_ref": "ipam:stat/ZGkMTAuMTQ4LjEyLjAvMjIvMA:default/10.158.2.0/22",
"comment": "VLAN 0",
"dhcp_utilization": 0,
"disable": false,
"enable_ddns": false,
"extattrs": {"CITY": {"value": "city" },
      "COUNTRY": {
        "value": "ABC"
      },
      "Helpnow ID": {
        "value": "TA"
            "value": 0
      }
    },
    "members": [],
    "network": "10.158.2.0",
    "utilization": 4
  },{"0": {"_ref": "ipam:stat/ZGkMQ4LjEyLjAvMjIvMA:default/10.109.2.0/22",
    "comment": "VLAN 0",
    "dhcp_utilization": 0,
    "disable": false,
    "enable_ddns": false,
    "extattrs": {
      "CITY": {
        "value": "city"
      },
      "COUNTRY": {
        "value": "CDS"
      },
      "Helpnow ID": {
        "value": "TA"
            "value": 0
      }
    },
    "members": [],
    "network": "10.109.2.0",
    "utilization": 9
  }]
nc1teljy

nc1teljy1#

列表理解应该可以完成这项工作,不需要filter()

>>> dic_of_dics = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}}

>>> list_of_dics = [value for value in dic_of_dics.values()]

>>>list_of_dics
[{'a': 'A'}, {'b': 'B'}, {'c': 'C'}]
rlcwz9us

rlcwz9us2#

这里只提到一个解决方案,它将与“id”关联的第一级“key”保存在下一级字典中。
换句话说,“把字典的字典转换成字典的列表,把钥匙放在里面”。

>>> dic_of_dics = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}}

>>> [(lambda d: d.update(id=key) or d)(val) for (key, val) in dic_of_dics.items()]
[{'a': 'A', 'id': 1}, {'b': 'B', 'id': 2}, {'c': 'C', 'id': 3}]
dgiusagp

dgiusagp3#

我知道这个问题有点老,但以防万一有人需要我一直在寻找的解决方案:
如果您希望保留外部指令的键,而不将它们作为内部指令中的值,则以下代码为每个内部指令生成一个元组列表(key, dict)

>>> dic_of_dics = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}}
>>> [(k,v) for k, v in dic_of_dics.items()]
[(1, {'a': 'A'}), (2, {'b': 'B'}), (3, {'c': 'C'})]

我用它通过add_nodes_from()函数从to_dict('index')函数从pandas生成的一个dict的dict中定义了一个networkx图,它工作起来很有魅力。

gc0ot86w

gc0ot86w4#

如果我很好地理解了这个问题,那么任务就是在不丢失数据结构的情况下,把字典中的字典变成字典列表。
list comprehension可以很好地实现这一点,其中列表中的每一项本质上都是字典的字典。

>>> dic_of_dicts = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}}
>>> [{k: v} for k, v in dic_of_dicts.items()]
[{1: {'a': 'A'}}, {2: {'b': 'B'}}, {3: {'c': 'C'}}]
gcuhipw9

gcuhipw95#

将字典的字典传递给list()更简洁、更快:

dic_of_dicts = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}}
list_of_dicts = list(dic_of_dics.values())
list_of_dicts
[{'a': 'A'}, {'b': 'B'}, {'c': 'C'}]

基准:

%timeit [value for value in dic_of_dics.values()]
153 ns ± 1.13 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

%timeit list(dic_of_dics.values())
95.3 ns ± 0.639 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

相关问题