首页 > 解决方案 > 如果不同,如何用另一个列表键值替换键值

问题描述

# list_one 
state_a = [
    {
        'state': 'California',
        'city': 'LA',
        'region': 'W'
    },
    {
        'state': 'Texas',
        'city': 'Austin',
        'region': 'SW'
    }
]

# list_two
state_b = [
    {
        'state': 'Florida',
        'city': 'Miami',
        'region': 'SE'
    },
    {
        'state': 'Texas',
        'city': ['Austin', 'Houston'],
        'region': 'E'
    }
]

如果键值不匹配,我想要一些关于如何找到和替换差异的帮助。这是我尝试过的,但一切都被替换了。我只想替换与 state_a 不同的部分。

result = []
for a in state_a:
    for b in state_b:
        if a['state'] == b['state']:
            result.append(a)

输出:

[
    {
        'state': 'Texas', 
        'city': 'Austin', 
        'region': 'SW'
    }
]

预期输出:

[
    {
        'state': 'Florida', 
        'city': 'Miami', 
        'region': 'SE'
    }, 
    {
        'state': 'Texas',
        'city': ['Austin', 'Houston'], 
        'region': 'SW' # only change in state_b to take effect
    }
]

如您所知,我只希望这会影响两个列表的不同之处,如果状态名称相等并进行更改,但仍保留其他数据。

标签: pythonlistloopsdictionary

解决方案


以下产生预期的输出。

result = []
for b in state_b:
    result.append(b)                            # Add state from b
    for a in state_a:
        if a['state'] == result[-1]['state']:   # Check last state added
            result[-1]['region'] = a['region']  # Update region
            break

推荐阅读