Python Forum

Full Version: Dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I get just numbers as int or float type from this dictionary named brand?

brand: {'BMW': 1983, 'Audi': 1986, 'Opel': 1992}
brand = {"BMW": 1983, "Audi": 1986, "Opel": 1992}
print(*brand.keys(), sep=", ")
print(*brand.values(), sum(brand.values()), sep=", ")
print(*brand.items(), sep=", ")
Output:
BMW, Audi, Opel 1983, 1986, 1992, 5961 ('BMW', 1983), ('Audi', 1986), ('Opel', 1992)
If your question is "how do I get all the numbers" and not "how do I get all the values", you can use a comprehension. This dictionary has two numbers. One is a key and the other a value.
brand = {"BMW": "1983", "Audi": 19.86, 1992: "Opel"}

all_numbers = [
    thing
    for thing in (*brand.keys(), *brand.values())
    if isinstance(thing, (int, float))
]
print(all_numbers)
Output:
[1992, 19.86]
Thanks! Smile
Next time read the documentation and you won't have to wait for an answer.

https://docs.python.org/3/library/stdtypes.html#dict

You would also learn about update(), get(), in, pop() and tons of other things Python dictionaries can do.