David H
David H

Reputation: 23

python print single instance of dictionary key value pairs after for loop

I'm using python 2.7 to loop through two dictionaries to swap key:value pairs between them. I am using a final for loop to recover average costs for a key that has an 'AND' operator.

list1 = {'dish1': ['apples', 'AND', 'pears'], 'dish2': ['oranges', 'AND', 'cherries'], 'dish3': ['carrots', 'OR', 'tomatoes']}
list2 = {'apples': '10', 'pears': '2', 'oranges': '5', 'cherries': '6', 'carrots': '5', 'tomatoes': '4'}

AND_List = {k:v for k, v in list1.items() if 'AND' in v}
DictList = {}
avgDict = {}

for k, v in AND_List.items():
  for j, i in list2.items():
    if j in v:
      DictList.setdefault(k, []).append(float(i))
    for k, i in DictList.iteritems():
      avgDict[k] = sum(i)/float(len(i))
    print avgDict

>>{'dish1': 6.0}
>>{'dish1': 6.0, 'dish2': 5.5}

I'd like the print statement after the last for loop to only print one instance of dish1 and dish2. It seems to be sequentially printing each conditionally recovered key:value. I'd appreciate any advice. Thanks!

Upvotes: 0

Views: 342

Answers (1)

gammazero
gammazero

Reputation: 953

I think your indents are incorrect. See if this is what you are looking for:

for k, v in AND_List.items():
    for j, i in list2.items():
        if j in v:
            DictList.setdefault(k, []).append(float(i))
    for k, i in DictList.iteritems():
        avgDict[k] = sum(i)/float(len(i))

print avgDict

Upvotes: 1

Related Questions