带有共同子键的新词典

时间:2014-04-09 09:29:39

标签: python dictionary

如果我有字典,如下:

{
    'key1':
        {
            'foo': 1233,
            'bar': 1234,
            'baz': 122
        },
    'key2':
        {
            'foo': 113,
            'bar': 333
        }
}

如何返回包含以下结果的新词典

{
    'key1':
        {
            'foo': 1233,
            'bar': 1234
        },
    'key2':
        {
            'foo': 113,
            'bar': 333
        }
}

我想要'key1'和'key2'的子词典(这是正确的术语?)具有相同的键

3 个答案:

答案 0 :(得分:4)

这应该这样做:

>>> d = { 'key1': { 'foo': 1233, 'bar': 1234, 'baz': 122 }, 'key2': { 'foo': 113, 'bar': 333 } }
>>> keys = (x.keys() for x in d.itervalues())
>>> common_keys = set(next(keys)).intersection(*keys)
>>> {k : {k_: v[k_] for k_ in common_keys} for k, v in d.iteritems()}

{'key2': {'foo': 113, 'bar': 333},
 'key1': {'foo': 1233, 'bar': 1234}}

答案 1 :(得分:1)

另一个答案:

def func(a):
    res = {}
    keys = a.keys()
    common = reduce(lambda x, y: x & y, [set(a[i].keys()) for i in keys])
    for k in keys:
        temp = {}
        for c in common:
            temp[c] = a[k][c]

        res[k] = temp

    return res

答案 2 :(得分:1)

我试图回答......真的不喜欢限制性的lambda:S

def result_get_mutual(result):
    return result_keep_mutual(
        result,
        result.iterkeys(),
        reduce(
            lambda current, incoming:
                current.intersection(incoming),
            map(
                lambda base_data: set(base_data[1].iterkeys()),
                result.iteritems())))


def result_keep_mutual(result, base_dict, sub_dict_common):
    return reduce(
        lambda current, base_data:
            base_get_common(current, base_data, sub_dict_common),
        result.iteritems(),
        {})

def base_get_common(result, base_data, sub_dict):
    result.update({
        base_data[0]: reduce(
            lambda result, sub_incoming:
                base_rebuild_ping(result, sub_incoming, base_data[1][sub_incoming]),
            sub_dict,
            {})
        });

    return result;

def base_rebuild_ping(result, sub, ping):
    result.update({ sub: ping })

    return result

print result_get_mutual({
    'key1':
        {
            'foo': 1233,
            'bar': 1234,
            'baz': 122
        },
    'key2':
        {
            'foo': 113,
            'bar': 333
        }
});