36

オブジェクト/dict(?) プロパティを新しいオブジェクト/dict に拡張するにはどうすればよいですか?

シンプルな Javascript:

const obj = {x: '2', y: '1'}
const thing = {...obj, x: '1'}
// thing = {x: '1', y: 1}

パイソン:

regions = []
for doc in locations_addresses['documents']:
   regions.append(
        {
            **doc, # this will not work
            'lat': '1234',
            'lng': '1234',

        }
    )
return json.dumps({'regions': regions, 'offices': []})
4

2 に答える 2

60

Python >=3.5を使用している場合、dictリテラルでキーワード展開を使用できます 。

>>> d = {'x': '2', 'y': '1'}
>>> {**d, 'x':1}
{'x': 1, 'y': '1'}

これは「スプラッティング」と呼ばれることもあります。

Python 2.7 を使用している場合、同等のものはありません。それは、7年以上前のものを使用する際の問題です. 次のようにする必要があります。

>>> d = {'x': '2', 'y': '1'}
>>> x = {'x':1}
>>> x.update(d)
>>> x
{'x': '2', 'y': '1'}
于 2017-12-18T20:25:09.943 に答える