Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—将数组中的值推送到字典_Python - Fatal编程技术网

Python—将数组中的值推送到字典

Python—将数组中的值推送到字典,python,Python,我需要根据数组中的键重建一个新字典。从现有字典。数组值将每次都更改 olddict = { "brand": "Ford", "model": "Mustang", "year": 1964, "createdby": "Mustang", "orderedby": "Mustang" } a

我需要根据数组中的键重建一个新字典。从现有字典。数组值将每次都更改

olddict =   {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "createdby": "Mustang",
  "orderedby": "Mustang"
}

arr = ['brand','year','createdby']
所需输出:

newdict=    {
  "brand": "Ford",
  "year": 1964,
  "createdby": "Mustang"
}
请尝试使用以下代码:

newdict = {param:olddict.get(param) for param in arr}

您可以使用词典理解技巧

newdict = {key:olddict[key] for key in arr}
其中,
key
arr
列表/数组中的所有内容,
newdict
的值是
oldict[key]


希望您觉得它简单实用您可以添加此功能:

def updated_dict(arr, olddict):
    newdict = {}
    for item in arr:
        newdict[item] = olddict.get(item)

    return newdict
def updated_dict(arr, olddict):
    newdict = {}
    for item in arr:
        newdict[item] = olddict.get(item)

    return newdict