继承字典中缺少的键(Python)

时间:2017-06-15 18:56:49

标签: python python-3.x dictionary

我正在创建一个Python3字典:

parents = {
    'parent_0': {
        'f_name': 'john',
        'l_name': 'doe',
        'location': 'New York, NY',
        'birth_month': 'september',
        'nationality': 'france',
        },
    'parent_1': {
        'f_name': 'jane',
        'l_name': '',
        'location': '',
        'birth_month': 'may',
        'nationality': ''
    },

}

parent_1如何从parent_0继承l_name,location和nationality的键值?

2 个答案:

答案 0 :(得分:2)

for key, value in parents['parent_1'].items():
    if not value:
        parents['parent_1'][key] = parents['parent_0'][key]

答案 1 :(得分:1)

for key in parents['parent_1'].keys:
    if parents['parent_1'] == '':
        parents['parent_1'][key] = parents['parent_0'][key]