user3210787
user3210787

Reputation: 157

What's the easiest way to print seleced key values from dictionary in python

I have a dictionary that contains several keys and values, ie:

d = {'1' : "whatever", '2' : "something", '3' : "other", '4' : "more" ...etc}

I would like to quickly print selected values from that code, for example values of following keys: 1,3,20,23,45,46 etc.

I know I can print value by value:

print d['1'] + d['3'] +d['20'] + d['23'] + d['45'] + d['46']

but that'll take to long to type and the number sequence is visually unclear. What would be the simplest way to print out selected values, while keeping the sequence visualy easy to read (ideally something like print d['1','3','20','23','45','46']?

Upvotes: 1

Views: 116

Answers (4)

Sylvain Leroux
Sylvain Leroux

Reputation: 51990

I'm surprised no one has proposed the obvious:

d = {'1' : "whatever", '2' : "something", '3' : "other", '4' : "more",
     '20': 'vingt', '23': 'vingt-trois', '45':'quarante-cinq', '46':'quarante-six' }
keys_to_print = ['1', '3', '20', '23', '45', '46']

print ' '.join([d[key] for key in keys_to_print])

Producing:

whatever other vingt vingt-trois quarante-cinq quarante-six

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

There are several ways to do this.

Using operator.itemgetter with str.join:

>>> from operator import itemgetter
>>> keys = ['1', '3', '4', '2']
>>> print ' '.join(itemgetter(*keys)(d))
whatever other more something
>>> print ' '.join(itemgetter('1', '3', '4', '2')(d)) #without a `keys` variable.
whatever other more something

Using str.join with a generator expression:

>>> print ' '.join(d[k] for k in keys)
whatever other more something

If you're using Python 3 or willing to import print function in Python 2:

>>> print(*itemgetter(*keys)(d), sep=' ')
whatever other more something
>>> print(*itemgetter('1', '3', '4', '2')(d), sep=' ')
whatever other more something
>>> print(*(d[k] for k in keys), sep=' ')
whatever other more something

Upvotes: 1

laurencevs
laurencevs

Reputation: 923

I think this solution is the easiest to understand:

keys_to_print = ['1', '3', '20', '23', '45', '46']
for key in keys_to_print:
    print d[key] + ' ',

This just loops through all of the keys whose values you want to print.

Upvotes: 1

grc
grc

Reputation: 23545

You could combine dict.get with the map function:

map(d.get, ['1', '3', '20', '23', '45', '46'])

This will give you a list of the corresponding values, such as:

['whatever', 'other', 'something', 'more']

You could print them with:

print ' '.join(map(d.get, ['1', '3', '20', '23', '45', '46']))

Upvotes: 2

Related Questions