Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary
#1
How can I get just numbers as int or float type from this dictionary named brand?

brand: {'BMW': 1983, 'Audi': 1986, 'Opel': 1992}
Reply
#2
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]
Reply
#3
Thanks! Smile
Reply
#4
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.
ndc85430 and freethrownucleus like this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020