Search code examples
pythonloopsdictionarystorekey-value

how to iterate over a dictionary from value in an array and store in a new dictionary


I have an array(Arr[]), for each item in the array i would like for it to go through a dictionary(specs{}) and calculate the corresponding values and store them in a new dictionary but on sure how to specify the key and value for this new dictionary {results{}).

Arr=["saucer", "shoes"]
def calc(Arr, context, user_results):
    results = {}
    for x in Arr:
        if x == specs.keys():
            results = specs.values
            results.append(x : results)
    return results

specs = {'cup': 3,'saucer': 5, 'bag': 17, 'shoes': 9}

results={"saucer": 5, "shoes": 9}


Solution

  • You could use a dict comprehension to build up a new dict using the items in specs

    results = {key: specs[key] for key in Arr if key in specs}