Home > database >  for loops within dictionaries vs dictionaries within for loops?
for loops within dictionaries vs dictionaries within for loops?

Time:11-17

Hi I have a question about iterating through a list and adding items and their frequency within the list to a dictionary.

i = ['apple','pear','red','apple','red','red','pear','pear','pear']
d = {x:i.count(x) for x in i} 
print (d)

outputs


{'pear': 4, 'apple': 2, 'red': 3}

However

i = ['apple','pear','red','apple','red','red','pear', 'pear', 'pear']
d = {} 
for x in i: 
    d={x:i.count(x)}
print(d)

outputs

{'pear': 4}

I need to iterate through the list while adding each iteration within the dictionary to a new list. However I can't understand why the two different codes are giving different results.

It's encouraging to seee that the count function works on the second one. But I am confused as to where apple and red dissapeared to.

Sorry for bad wording etcetera been working on this hours and is driving me crazy. Thanks so much for taking time to help

I am confused as to why the two results are different

CodePudding user response:

i = ['apple','pear','red','apple','red','red','pear', 'pear', 'pear']
d = {} 
log = []
for x in i: 
    log.append({x:i.count(x)})

log is

[{'apple': 2},
 {'pear': 4},
 {'red': 3},
 {'apple': 2},
 {'red': 3},
 {'red': 3},
 {'pear': 4},
 {'pear': 4},
 {'pear': 4}]

CodePudding user response:

I just ran your first bit of code and it gave me

{'apple': 2, 'pear': 4, 'red': 3}

which is correct but differs from what you've stated in the question.

To address your second bit of code, you're performing assignment operation on each iteration of the loop, so the value of d is being re-written every time you access a new item of i

Personally I would recommend using Counter for this problem:

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

CodePudding user response:

The problem is that you must add key:value pairs in the second loop instead of overwriting d with every loop.

i = ['apple','pear','red','apple','red','red','pear','pear','pear']
d = {}

for x in i:
    d[x] = i.count(x)

print(d)

will output the same as your first function.

{'pear': 4, 'apple': 2, 'red': 3}

Basically in your second example when you do d={x:i.count(x)} you have a one element dictionary and for every loop you overwrite that. Then it only shows pear: 4 because pear is the last element in your i list.

CodePudding user response:

varLs = ['apple','pear','red','apple','red','red','pear','pear','pear']

def frequency(varLs):  
    counters = {}

    for item in varLs:
        if item not in counters:
            counters[item] = 1
        else:
            counters[item] = 1
    return counters

print(frequency(varLs))

returns {'apple': 2, 'pear': 4, 'red': 3}

  • Related