0

Say we have this:

dict = {1:[2, 3]}
m = 4
new = {1:[]} # to save time, the keys in "new" were obtained from "dict"

I wanna use "dict" to make "new" so each of the values appear in list of "dict" as many times as "m" so that:

new = {1:[2, 2, 2, 2, 3, 3, 3, 3]} # values appear "m" times

How can I achieve this by using for loops? It gets kinda confusing for me as I used a lot of for loops, any help would be appreciated. I would prefer if you guys give ideas rather that give me the code.

HoopsMcCann
  • 315
  • 1
  • 3
  • 16

4 Answers4

3
data = {1: [2,3]}
m = 4
new = {k:[n for n in lst for i in range(m)] for k,lst in data.items()}
Hugh Bothwell
  • 53,141
  • 7
  • 81
  • 98
2

if you don't care about order:

data = {1: [2,3]}
m = 4

# gives {1:[2,3,2,3,2,3,2,3]}
new_data = { k:v*m for k,v in data.items()}
bcorso
  • 43,538
  • 9
  • 62
  • 75
0

replicating elements in list should give you a good idea of how to proceed in this case.

Python allows you to just "multiply" whatever you want to repeat by the number of repetitions.

edit: Wow.. wait - didn't you post on the "replicating elements in list-thread" already?

Community
  • 1
  • 1
fuesika
  • 3,200
  • 6
  • 25
  • 34
0
>>> from itertools import chain, repeat
>>> data = {1: [2,3]}
>>> m = 4
>>> {k: list(chain.from_iterable(repeat(i, m) for i in data[k])) for k in data}
{1: [2, 2, 2, 2, 3, 3, 3, 3]}
John La Rooy
  • 281,034
  • 50
  • 354
  • 495