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

时间:2017-09-26 09:08:03

标签: python python-2.7 dictionary

我有一本字典词典:

from import_export import resources, fields
from import_export.widgets import ForeignKeyWidget

class DataResource(resources.ModelResource):
    # UPDATE
    # If model has ForeignKey
    station = fields.Field(widget=ForeignKeyWidget(station, 'id'))

    def get_instance(self, instance_loader, row):
        # Returning False prevents us from looking in the
        # database for rows that already exist
        return False

    class Meta:
        model = assets # class name should be camelcase
        fields = '__all__' # If all column of table present in xlsx otherwise mention fields name.

@admin.register(assets)
class data_import(ImportExportModelAdmin):
    resource_class = DataResource

我想将其转换为:

d = {"a": {"x":1, "y":2, "z":3}, "b": {"x":2, "y":3, "z":4}, "c": {"x":3, "y":4, "z":5}}

要求是new_d = {"x":[1, 2, 3], "y": [2, 3, 4], "z": [3, 4, 5]} new_d[key][i]应位于new_d[another_key][i]的同一子词典中。

所以我创建了d然后:

new_d = {}

这给了我我的预期,但我只是想知道这个操作是否有一些内置函数,或者有更好的方法。

2 个答案:

答案 0 :(得分:6)

此操作没有内置功能,没有。我只是直接遍历values

new_d = {}
for sub in d.itervalues():              # Python 3: use d.values()
    for key, value in sub.iteritems():  # Python 3: use d.items()
        new_d.setdefault(key, []).append(value)

这样可以避免每次都为dict.values()调用创建新列表。

请注意,词典没有订单。结果列表中的值将符合您的标准;对于new_d中的每个键,它们将以相同的顺序添加:

>>> d = {"a": {"x":1, "y":2, "z":3}, "b": {"x":2, "y":3, "z":4}, "c": {"x":3, "y":4, "z":5}}
>>> new_d = {}
>>> for sub in d.values():
...     for key, value in sub.items():
...         new_d.setdefault(key, []).append(value)
...
>>> new_d
{'x': [1, 2, 3], 'y': [2, 3, 4], 'z': [3, 4, 5]}

答案 1 :(得分:0)

列表理解方法

如果您喜欢字典和列表理解...

d1 = {"a": {"x": 1, "y": 2, "z": 3},
      "b": {"x": 2, "y": 3, "z": 4},
      "c": {"x": 3, "y": 4, "z": 5}}

dl1 = {kl: [v for di in d1.values() for k, v in di.items() if k == kl]
       for di in d1.values() for kl in di.keys()}

print(dl1)

并产生希望的结果...

{'x': [1, 2, 3], 'y': [2, 3, 4], 'z': [3, 4, 5]}
相关问题