Home > Software engineering >  Store contents of two lists as key-value pairs in a dictionary
Store contents of two lists as key-value pairs in a dictionary

Time:09-29

I have two Python lists. One list, called area, stores the areas of homes. Different homes may have the same area. Another list, called price, stores the corresponding prices of these homes. I want to create a dictionary called priceDict, whose keys are the unique areas of homes and whose values are lists of the prices of homes of the same area. For example, suppose area = [1500, 500, 1500, 2000, 2500, 2000], price = [30000, 10000, 20000, 40000, 50000, 45000]. I would like to create the dictionary priceDict = {1500: [30000, 20000], 500: [10000], 2000: [40000, 45000], 2500: [50000]}.

I wrote the following Python code:

area = [1500, 500, 1500, 2000, 2500, 2000]
price = [30000, 10000, 20000, 40000, 50000, 45000]
priceDict = dict.fromkeys(area,[])
    
for houseArea in priceDict:
    for areaIndex in range(len(area)):
        if area[areaIndex] == houseArea:
            priceDict[houseArea].append(price[areaIndex])

print(priceDict)

However, when I executed the code, the output I got was:

{1500: [30000, 20000, 10000, 40000, 45000, 50000], 500: [30000, 20000, 10000, 40000, 45000, 50000], 2000: [30000, 20000, 10000, 40000, 45000, 50000], 2500: [30000, 20000, 10000, 40000, 45000, 50000]}

I would like to ask what's wrong with my code and how I can re-write my code so that it performs the intended function.

CodePudding user response:

Your first problem is here:

priceDict = dict.fromkeys(area,[])

This makes every key in priceDict share the same list.

The second problem is you are nesting for-loops rather than using a single for-loop and zipping to pair up your items:

priceDict = {}
for k, v in zip(area, price):
    priceDict.setdefault(k, []).append(v)

Note that priceDict.setdefault(k, []).append(v) is slightly inefficient because it creates an empty list on every iteration. A more efficient way is to use a defaultdict of list.

from collections import defaultdict

priceDict = defaultdict(list)
for k, v in zip(area, price):
    priceDict[k].append(v)
  • Related