0

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

Franc42
  • 11
  • 3
  • 1
    The answers already give great insight. Just to rephrase this for whoever finds it helpful. In the first code block, you are giving the instruction "add this key:pair to the dictionary `d`". In the loop, you are giving the instruction: "Assign this dictionary with key:pair to a variable called `d`". Since the loop assigns it multiple times, only the last assignment remains. – Mitchell van Zuylen Nov 17 '22 at 00:49
  • Also, none of the answers address the big problem with even your first code: `i.count(x)` iterates over _all_ elements in the `i` list. Running it for each `x` in `i` means your code is O(n^2). You could have just iterated over the list, and `d[x] += 1` for each `x` in `i`, and your code would have been O(n). Or, just use `collections.Counter`, which does the same thing (one answer recommends this, but doesn't explain why) – Pranav Hosangadi Nov 17 '22 at 01:23

4 Answers4

2

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.

user99999
  • 310
  • 1
  • 13
0
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}]
Ricardo
  • 691
  • 3
  • 11
0

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})
  • The reason that it gave you a different output is because dictionaries are unordered and will print in any random order. The output you got was perfectly correct and normal. – user99999 Nov 17 '22 at 00:41
  • Dictionaries have been insertion-ordered since Python 3.7. https://stackoverflow.com/q/39980323/843953 @user99999 – Pranav Hosangadi Nov 17 '22 at 01:17
  • I originally meant the difference to be in the "pear" count @user99999, but OP corrected that in the question. The answer you gave is correct though ) – Nazar Nintendo Nov 17 '22 at 07:59
-1
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}

Meer Modi
  • 21
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 19 '22 at 10:30