如何保留python字典值

时间:2018-04-20 00:29:47

标签: python dictionary

我正在尝试从下面的列表创建一个字典,我只需要2个值,我希望它们作为键和值。它只打印列表中的最后一个字典值并且缺少'key':'earthquake'

{'locale': 'Raj', 'latlng': 'Sahu', 'include': 'website', 'agent': 'Pramod'}

我希望它能打印

{'locale': 'Raj', 'latlng': 'Sahu', 'include': 'website', 'agent': 'Pramod', 'key':'earthquake'}

我在这里缺少什么?

parameters = [
                    {
                        "type": "0",
                        "name": "key",
                        "value": "earthquake"
                    },
                    {
                        "type": "0",
                        "name": "include",
                        "value": "website"
                    }
                ]
    def create():
        for parameter in parameters:
            params = {parameter.get('name'):parameter.get('value')}
        params["locale"] = "Raj"
        params["agent"] = "Pramod"
        params["latlng"] = "Sahu"
        print params
        return params

    if __name__ == '__main__':
        create()

3 个答案:

答案 0 :(得分:2)

You are replacing your dict in each loop iteration. Try putting your declaration above the for loop then adding the key and value to it on each iteration like so

params = {}
for parameter in parameters:
    param[parameter.get('name')] = parameter.get('value')
params['locale'] = 'raj'
# ...

答案 1 :(得分:0)

You're iterating over the list of dictionaries. So on the second pass it sets the key to include and the value to website. You need to initialize a dictionary above the loop where results will be stored otherwise you will keep overwriting it. You can also do this:

params = {}
params["locale"] = "Raj"
params["agent"] = "Pramod"
params["latlng"] = "Sahu"

for parameter in parameters:
    params.update({parameter.get('name'):parameter.get('value')})

答案 2 :(得分:0)

using comprehension, you could do:

params = { p.get('name'):p.get('value') for p in parameters if p.get('value') == 'earthquake' }
params['locale'] = 'raj'
# ...