简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM