使用匹配的键:值对加入Python词典

时间:2014-09-07 20:54:25

标签: python dictionary

说我有这样的字典列表字典:

{
    customers:[{customername:"Bob", age:32}],
    addresses:[{customername:"Bob", address:"123 Seseme street",addressname:"home"},
               {customername:"Bob", address:"543 42nd street", addressname:"Work"}],
    phonenumbers:[{customername:"Bob", phone:1234567, phonename:"Cell"}]
]

我想在所有其他词典中创建一个新词典,其中包含键:值对' customername:" Bob"':

Bob = {customername:"Bob", address:[{addressname:"home",address:"123 Seseme street"},
                                    {addressname:"Work", address:"543 42nd street"}],
       phone:{phonename:"Cell", phone:1234567}

第一个问题:如何以最优雅的方式创建这个新词典?

第二个问题:有没有办法将这些连接到包含一些任意数量的词典的顶级词典,而不是所有词典都包含该特定键?

1 个答案:

答案 0 :(得分:3)

布里奥尼乌斯是对的,这比起初看起来容易:

l = [[x for x in db[x] if x['name']=='bob'] for x in db]
bob = [item for sublist in l for item in sublist

如果我决定保留顶级词典,这可行:

{key:value for (key,value) in db.iteritems() for item in value if item['name']=='bob'}