Understanding code


##

# Determine whether or not two strings are anagrams and report the result.

#

## Compute the frequency distribution for the characters in a string

# @param s the string to process

# @return a dictionary mapping each character to its count

def characterCounts(s):

# Create a new, empty dictionary

    counts = {}

# Update the count for each character in the string

    for ch in s:

        if ch in counts:

            counts[ch] = counts[ch] + 1

        else:

            counts[ch] = 1

# Return the result

    return counts

print(characterCounts("evil"))

Am trying to understand what this part of the code is doing. I tried using print statement but its giving me a syntax error


counts = {'apple':1,'peach':2,'apricot':3,'kiwi':4,'passion':5 }

counts = counts['apple'] + 1)

print(counts.items())

This line is going to cause an issue.

counts = counts['apple'] + 1)

Dictionary’s may look similar in usage to lists but the similarities are superficial.
If you want to update an item in a current dictionary:

my_dic["my_item_in_dic"] = new_value

or

my_dic["my_item_in_dic"] = my_dic["my_item_in_dic"] + transformation

(note the transformation doesn’t have to use the + operator, can use a method/function or any other operator)

1 Like