Home > Blockchain >  Print key AND value if key matches input?
Print key AND value if key matches input?

Time:04-04

I have a dictionary and a for loop to print:

car_dict = {'Sports':{'Audi':'A4', 
           'Ferarri':'Spider'}}

for key, value in car_dict.items():
         if key == 'Sports':
             print(key, value) 

So, if input == "Sports", it will print:

Sports {'Audi': 'A4', 'Ferarri': 'Spider'}

How do I print it so it looks like:

-Sports-
Audi A4
Ferrari Spider

with a small heading (not necessary), on top of one another and without dict syntax? I've been messing around with it for a while now and can't seem to find a resolution. This is my furthest! thanks

CodePudding user response:

You could iterate over the value if the key is "Sports":

for key, value in car_dict.items():
    if key == 'Sports':
        print('-', key)
        for pair in value.items():
            print(*pair)
        

Output:

- Sports
Audi A4
Ferarri Spider

CodePudding user response:

I would factor the printing out to another method as you likely will have multiple categories of cars.

Additionally you can use f-strings to easily format the output.

You might also wanna consider using multi line strings using """ in combination with f-strings to have nice multi line output. See the example below.

car_dict = {
    'Sports': {'Audi': 'A4', 'Ferarri': 'Spider'}
}


def print_category(cat_name, cars):
    print(f"- {cat_name} -")
    for (brand, model) in cars.items():
        print(brand, model)


def print_category_multiline(cat_name, cars):
    print(f"""
 --------------------------- 
 {cat_name} 
 --------------------------- """)
    for (brand, model) in cars.items():
        print(brand, model)


for key, value in car_dict.items():
    print_category(key, value)
    print_category_multiline(key, value)

Expected output

- Sports -
Audi A4
Ferarri Spider

 --------------------------- 
 Sports 
 --------------------------- 
Audi A4
Ferarri Spider

The if condition you have in your for loop is currently not really doing anything, as you only have the sports category of cars, hence you do not need it. If you wanted to do some filtering of categories (when you have more categories) I would certainly create a set of categories and check in the for loop if the the current category is within the filter or not. This could look be done like this:

cat_filter = {"Sports", "Offroad"}

for key, value in car_dict.items():
    # only print filtered values
    if key in cat_filter:
        print_category(key, value)
        print_category_multiline(key, value)
  • Related