PV8
PV8

Reputation: 6260

Create list / text of repeated strings based on dictionary number

I have the following dictionary:

mydict = {'mindestens': 2,
 'Situation': 3,
 'österreichische': 2,
 'habe.': 1,
 'Über': 1,
 }

How can I get a list / text out of it, that the strings in my dictionary are repeated as the number is mapped in the dictionary to it:

mylist = ['mindestens', 'mindestens', 'Situation', 'Situation', 'Situation',.., 'Über']
mytext = 'mindestens mindestens Situation Situation Situation ... Über'

Upvotes: 1

Views: 40

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

itertools library has convenient features for such cases:

from itertools import chain, repeat

mydict = {'mindestens': 2, 'Situation': 3, 'österreichische': 2,
          'habe.': 1, 'Über': 1,
          }

res = list(chain.from_iterable(repeat(k, v) for k, v in mydict.items()))
print(res)

The output:

['mindestens', 'mindestens', 'Situation', 'Situation', 'Situation', 'österreichische', 'österreichische', 'habe.', 'Über']

For text version - joining a list items is trivial: ' '.join(<iterable>)

Upvotes: 1

q84fh
q84fh

Reputation: 51

You might just use loops:

mylist = []
for word,times in mydict.items():
    for i in range(times):
        mylist.append(word)

Upvotes: 2

Related Questions