Reputation: 133
lets say that there is a dict given:
cars = {
"brand": ["BMW", "Mercedes", "Audi", "Renault"],
"model": ["M4", "a35", "rs7", "Megane"],
"year": [2016, 2014, 2017, 2013],
}
How do i print it so the expected output would be: BMW M4 2016, Mercedes a35 2014, Audi rs7 2017 etc..
Of course you can change the dictionary if its wrong writtent, but i am just asking how to do like a data structure dictionary with cars.
Upvotes: 0
Views: 1336
Reputation: 5935
You can create a class Car
to represent a car, so all the attributes are actually part of the object they belong to, not stored in seemingly unrelated lists.
The next advantage is that you can expand the object with new attributes later on, and you can use methods to do work on it. And if done correctly, all the code outside of the class will still work after a change, because all the implementation details are handled in class Car
.
For example you can "teach" a Car
how to print itself, by implementing a __str__
method, so your printing code does not need to know anything about the "inside" of your class to print it, and you can change the implementation of __str__
later, without having to touch the code outside doing the printing.
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def __str__(self):
return f'{self.brand}, {self.model}, {self.year}'
cars = [
Car('BMW', 'M4', 2016),
Car('Mercedes', 'a35', 2014),
Car('Audi', 'rs7', 2017),
Car('Renault', 'Megane', 2013)
]
for car in cars:
print(car)
"""
BMW, M4, 2016
Mercedes, a35, 2014
Audi, rs7, 2017
Renault, Megane, 2013
"""
for car in cars:
print(car.year)
"""
2016
2014
2017
2013
"""
You can easily convert your dictionary of lists into a list of Car
instances by using the other solution in this post:
cars = {
"brand": ["BMW", "Mercedes", "Audi", "Renault"],
"model": ["M4", "a35", "rs7", "Megane"],
"year": [2016, 2014, 2017, 2013],
}
car_classes = [Car(*args) for args in zip(cars['brand'], cars['model'], cars['year'])]
Upvotes: 2
Reputation: 456
You can re-write the dictionary as a list of dictionaries. As noted in the comments above, probably best to avoid using positional relations.
cars = [
{"brand": "BMW", "model": "M4", "year": 2016},
{"brand": "Mercedes", "model": "a35", "year": 2014},
{"brand": "Audi", "model": "rs7", "year": 2017},
{"brand": "Renault", "model": "Megane", "year": 2013},
]
for car in cars:
print(car["brand"], car["model"], car["year"])
OUTPUT:
BMW M4 2016
Mercedes a35 2014
Audi rs7 2017
Renault Megane 2013
Upvotes: 1
Reputation: 3121
You can use simply a zip
function then print it.
cars = {
"brand": ["BMW", "Mercedes", "Audi", "Renault"],
"model": ["M4", "a35", "rs7", "Megane"],
"year": [2016, 2014, 2017, 2013],
}
for c,m,y in zip(cars['brand'],cars['model'],cars['year']):
print(c,m,y)
Upvotes: 4