Home > OS >  How to print values from dictionary of your choice in a single line ? IN PYTHON
How to print values from dictionary of your choice in a single line ? IN PYTHON

Time:05-18

Suppose this is a dictionary : {'name': 'Instagram', 'follower_count': 346, 'description': 'Social media platform', 'country': 'United States'}

and i want my output like : Instagram, Social media platform, United States

how do i achieve this?

CodePudding user response:

I think this is what you're looking for?

import operator

items_getter = operator.itemgetter('name', 'description', 'country')
print(', '.join(items_getter(dictionary)))

CodePudding user response:

You can use operator.itemgetter:

from operator import itemgetter

dct = {'name': 'Instagram', 'follower_count': 346, 'description': 'Social media platform', 'country': 'United States'}
print(*itemgetter('name', 'description', 'country')(dct), sep=', ')
# Instagram, Social media platform, United States

Alternatively, if for some reason you don't want to use itemgetter:

print(dct['name'], dct['description'], dct['country'], sep=', ')

CodePudding user response:

This is the simplest way you can get what you want:

dct = {
    'name': 'Instagram', 
    'follower_count': 346, 
    'description': 'Social media platform', 
    'country': 'United States'
}

print(f'{dct['name']}, {dct['description']}, {dct['country']}')

Output:

Instagram, Social media platform, United States

CodePudding user response:

Use the key in condition to whatever value you want to eliminate

for i in thisdict:
    if i == "follower_count":
        continue
    else:
        print(thisdict[i])

Or you may also use .items method to get key,values and then continue

for k,v in thisdict.items():
    if k=="follower_count":
        continue
    else:
        print(v)
  • Related