This is homework:
fruits = {'banana':3,'apple':2, 'mango':1, 'kiwi':5}
This is the result I'm supposed to get:
fruits_list = [
['banana', 'banana', 'banana'],
['apple', 'apple'],
['mango'],
['kiwi', 'kiwi', 'kiwi', 'kiwi', 'kiwi']]
You need to iterate all over fruits keys and build a list repeating the key N=value
times.
You can accomplish this with a list comprehension.
fruits.items()
.[key]*N
.[key]*value
.Finally:
fruits_list = [[key]*value for key, value in fruits.items()]
Then print(fruit_list)
gives you:
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
[['banana', 'banana', 'banana'], ['apple', 'apple'], ['mango'], ['kiwi', 'kiwi', 'kiwi', 'kiwi', 'kiwi']]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments