1

Hello I define a class person as following:

class Person(object):
    def __init__(self, X, Y):
        self.name = X
        self.city = Y
names = ['Bob', 'Alex', 'John']
cities = ['New York', 'London', 'Rome']
N = list()
for i in range(0,3):
    x = names[i]
    y = cities[i]
    N.append(Person(x,y))

I want to to check the corresponding cities of a name automatically, something like this

N.name['Bob'].city =
'New York'
1
  • 1
    Not possible with classes (in current form). If there's a one-one relation (or one-many), then consider using dictionaries. Commented Nov 16, 2015 at 17:53

2 Answers 2

2

Create a dictionary with name as key:

class Person(object):
    def __init__(self, name, city):
        self.name = name
        self.city = city
names = ['Bob', 'Alex', 'John']
cities = ['New York', 'London', 'Rome']

persons = {n: Person(n,c) for n,c in zip(names, cities)}

print(persons['Bob'].city)
Sign up to request clarification or add additional context in comments.

Comments

2

Use python dictionaries

people = {}
names = ['Bob', 'Alex', 'John']
cities = ['New York', 'London', 'Rome']
if len(names) != len(cities):
  # You might want to do something other than a base exception call here
  raise Exception('names and cities must be of equal size')
for i in range(len(names)):
  people[names[i]] = cities[i]
print(people['Bob'])

>>>'New York'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.