rpiboy
Posts: 110
Joined: Mon Mar 20, 2017 8:39 pm

Print a specific key, value for loop dictionary

Mon Apr 15, 2019 9:43 pm

Code: Select all

class Options:
    default_options = {
        'port': 21,
        'host': 'localhost',
        'username': None,
        'password': None,
        'debug': False,
        }
    def __init__(self, **kwargs):
        self.options = dict(Options.default_options)
        self.options.update(kwargs)
    
    def __getitem__(self, key):
        return self.options[key]

Code: Select all

options = Options.default_options
for key, value in options['port', 'host']:
print(value)
I get a Key error I was wondering if it was possible to print a specific value from the dictionary using for loop.
I've googled but didn't find anything.

PhatFil
Posts: 1421
Joined: Thu Apr 13, 2017 3:55 pm
Location: Oxford UK

Re: Print a specific key, value for loop dictionary

Mon Apr 15, 2019 10:38 pm

Try

Code: Select all

options = Options.default_options
for key in options:
 if key =="port" or key == "host":
 print(value)

SavinaRoja
Posts: 5
Joined: Mon Apr 01, 2019 1:31 am

Re: Print a specific key, value for loop dictionary

Tue Apr 16, 2019 3:26 am

If you want to print a few specific key-value pairs from a dict based on the key, you may consider this (it seems you were pretty close to this):

Code: Select all

options = Options.default_options
for key, value in options.items():
    if key in ['port', 'host']:
        print('{}: {}'.format(key, value))

Return to “Python”