Niels Gorsel
Niels Gorsel

Reputation: 377

Python - dictionary print the key as many times as his value

I want to print out all the letters in my dictionary (seen at the last line of my code) the problem is that the output is aqlmui now. But as you guys can see the l in my dictionary is having a value of 2 so I want to print that out 2 times. so the output of my program should be: aqllmui.

Help would be appreciated a lot! :)

def display_hand(hand):

    row = ''
    for letter in hand:
        row += letter

       #I think i need to put an if statement here but I just don't know how to do it

    print row


display_hand({'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1})

Upvotes: 0

Views: 2228

Answers (4)

Agustin Olano
Agustin Olano

Reputation: 1

For me, this was the most straightforward answer I could've found

def display_hand(hand: dict[str, int]) -> None:
    for letter in hand.keys():
        for i in range(hand[letter]):
            print(letter, end=" ") 

Upvotes: 0

Sainath Motlakunta
Sainath Motlakunta

Reputation: 945

You can also try print "".join(k*v for (k,v) in s.iteritems()).

Here k*v for (k,v) in s.iteritems() returns a list of key*value like ["a","i","m","ll","q","u"] and "".join(list) will join that list to make a string.

Upvotes: 2

chepner
chepner

Reputation: 531135

You can use string/int multiplication to perform multiple concatenations

for letter in hand:
    row += letter * hand[letter]

Or a little more clearly and efficiently:

for letter, count in hand.iteritems():  # Use hand.items() in Python 3
    row += letter * count

Upvotes: 1

kindall
kindall

Reputation: 184171

just do:

row += letter * hand[letter]

Upvotes: 1

Related Questions