Natalie
Natalie

Reputation: 63

explanation of this one line expression in python

I am learning python, and I saw a one-line python expression, but I don't really understand it. Can someone help explain the code to me? or expand the code in a traditional for loop? more specifically, what does {fruit: mean ?

return {fruit: basket.count(fruit) for fruit in set(basket)}

thanks!

Upvotes: 2

Views: 793

Answers (5)

jeremye
jeremye

Reputation: 1388

This expression is called a dict comprehension (essentially, a single-line expression that creates a dictionary).

In Python a dict looks like this:

dictionary = {"key": "value", "anotherkey": ["some", "other", "value"]}

Where the right side of the : is the key (usually a string), and the left side of the : is the value assigned to the key.

You can use the dictionary to get a value from a key like this:

dictionary["key"]
>> "value"

So, a dict comprehension builds a dictionary using some expression like the one in your example.

If you have this basket:

basket = ["apple", "apple", "banana"]
set(basket)  # set() returns a set of unique items from basket.
>> {"apple", "banana"} 
basket.count("apple")  # list.count(x) returns the number of times x occurs in list.
>> 2

This:

dictionary = {}
for fruit in set(basket):
    dictionary[fruit] = basket.count(fruit)
return dictionary

is the same as this:

return {fruit: basket.count(fruit) for fruit in set(basket)}
#      {^key : ^value}  is added   for each item in set(basket)           

and they both return:

{"apple": 2, "banana": 1}

Upvotes: 2

Sraw
Sraw

Reputation: 20214

It is equivalent with:

temp_dict = {}
for fruit in set(basket):
    temp_dict[fruit] = basket.count(fruit)
return temp_dict

Upvotes: 0

Paul Rooney
Paul Rooney

Reputation: 21609

What you have is a dict comprehension. It builds a dictionary from an iterable in a single statement. They were introduced in pep-0274.

So for each element in the iterable we create a dict entry. With the fruit as the key and the number of times it occurs in the list as the value.

here is an example. I have assumed the content of your variable basket.

basket = ['banana', 'apple', 'orange', 'cherry', 'orange', 'banana', 'orange', 'orange']

print( {fruit: basket.count(fruit) for fruit in set(basket)})

# or expanded as regular loop
d = {}
for fruit in set(basket):
    d[fruit] = basket.count(fruit)

print(d)

The count method is not very efficient, especially when coupled with another loop over the collection itself. A more efficient approach would be to use defaultdict.

from collections import defaultdict

dd = defaultdict(int)

for fruit in basket:
    dd[fruit] += 1

print(dd)

Now you iterate over the collection once exactly. Rather than once to create a set, once over the set itself and once over the list for each item in the set.

Upvotes: 1

Hugo G
Hugo G

Reputation: 16496

The code creates a dictionary that tells you the count of every fruit from the basket.

Maybe I can make it easier to understand by breaking it down. The code below is equivalent to your one-liner:

basket = ["apple", "apple", "pear", "banana"]

# a set is an unsorted list of unique items
uniqueFruits = set(basket)

# initialise empty dict
counts = {}

# loop through every unique fruit
for fruit in uniqueFruits:

    # how often does it come up in the basket?
    occurrences = basket.count(fruit)

    # put that number into the dict with the fruit name as value
    counts[fruit] = occurrences

Now the object counts contains the same dictionary as the one your statement returns. In our example:

{'pear': 1, 'banana': 1, 'apple': 2}

Upvotes: 2

Mohd
Mohd

Reputation: 5613

It is a dict comprehension to form a dictionary from baset list which makes the fruit name the key and the count of that fruit the value. A for loop for that would be:

basket = ['banana', 'banana', 'apple', 'banana', 'orange', 'apple']
d = {}
for fruit in set(basket):
    d[fruit] = basket.count(fruit)

# d = {'banana': 3, 'apple': 2, 'orange': 1}

x = {fruit: basket.count(fruit) for fruit in set(basket)}

# x = {'banana': 3, 'apple': 2, 'orange': 1}

Upvotes: 0

Related Questions