Question

Hello I am a new programmer so I dont know the computer sciency, pythonic way of saying it.. But what I am looking for is maybe a method or a loop function that is able to append to a dictionary.

What I have tried is a for loop function where I say

'K' = 0 + 1

and each time the func loops it adds a 1 till 10 then it stops... because I want the word to be repeated only 10 times... but now I am stuck, how do I get the word to be repeated 10 times.

Because remember this is a dictionary example:

{Words:['hi', 'bye', 'goodbye']}

I want each word to be repeated 10 times and appended to the a dictionary.

Sorry if my question seems like its just asking u to do this problem for me.

EDIT:

input:

    {Words:['hi', 'bye', 'goodbye']}

output:

     {Words:['hi','hi','hi','hi','hi','hi','hi','hi','hi','hi', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'goodbye','goodbye','goodbye','goodbye','goodbye','goodbye','goodbye','goodbye','goodbye','goodbye']}

as you can see each word is now repeated 10 times in the new dictionary.

Was it helpful?

Solution

num, mydict = 10, {"Words":['hi', 'bye', 'goodbye']}
print {k: [i for i in v for j in range(num)] for k, v in mydict.items()}

Output

{'Words': ['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'bye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye', 'goodbye']}

OTHER TIPS

Another way:

d = {'Words':['hi', 'bye', 'goodbye']}
new_d = {}
for key in d:
    new_d[key] = []
    for element in d[key]:
        new_d[key] += [element]*10

print new_d
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top