Page 1 of 1

Print a specific key, value for loop dictionary

Posted: Mon Apr 15, 2019 9:43 pm
by rpiboy

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.

Re: Print a specific key, value for loop dictionary

Posted: Mon Apr 15, 2019 10:38 pm
by PhatFil
Try

Code: Select all

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

Re: Print a specific key, value for loop dictionary

Posted: Tue Apr 16, 2019 3:26 am
by SavinaRoja
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))