In Python how do I use a for loop, to create nested list from dictionary?

A J E

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']]
Cheche

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.

  • To iterate all over dict items you'll need fruits.items().
  • To build a list repeating each key N times do: [key]*N.
  • As dict values indicate how many times to repeat, do: [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.

edited at
0

Comments

0 comments
Login to comment

Related

How to create a nested dictionary from a list in Python?

How do I remove certain keys from a nested dictionary in Python?

How do I create a list of Python lambdas (in a list comprehension/for loop)?

How do i create a nested dictionary iteratively?

Python: How do I remove elements from a dictionary and return it as a list?

How can I create a nested dictionary using a for loop in Python?

Create dictionary from a nested list

how do i make a nested dictionary in python?

How do I use a for loop when reading from a dictionary that might contain a list of dicts, but might not?

How do I remove a dictionary index from a list on Python?

How do I use numbers in a list as keys for my dictionary in Python?

Python - create dynamic nested dictionary from list of dictionary

How do i extract from a nested dictionary?

How do I create a dictionary from a .txt file with whitespace in python

How do I remove Spaces from nested list created with for loop?

How do I create a dictionary from a csv using python

How to create a nested dictionary from a list of lists

How do I remove string '' from python dictionary list values?

Python create dictionary from nested class in list

How to create a dictionary from a nested list of dictionary

How do I create a Pandas Dataframe from a dictionary containing a nested dictionary?

How do i create a nested list in Python

How do I extract strings from a nested dictionary in Python

Create a list of values from nested dictionary Python

How Do I return Nested Loop from a function in Python?

How to create a nested dictionary from multiple list?

how do I create dataframe from list of nested dictionary

How to create a nested dictionary from a string list (Python)?

Python - Create Dictionary From Nested List and Dictionaries