variable call through combination string python

Viewed 95

I have 2 lists dependent on each other like a person and where is he/she from. I want to make groups based on where they are from.

People = ["A","B","C","D","E","F"]
City = ["Bombay","Delhi","Pune","Pune","Bombay","Pune"]

Here, A is from Bombay, B is from Delhi, and like that. I want to group all people from Bombay in one group, Delhi in one group, and Pune in one group. Then I want to assign some task to each group, like people from Bombay will do task X, people from Delhi will do task Y, and people from Pune will do task Z. How can I do that in python?

A group is like a list. Example:

Bombay = ["A","E"]
Delhi = ["B"]
Pune = ["C","D","F"]
5 Answers

Using itertools.groupby

from itertools import groupby

data = sorted(zip(People, City), key=lambda x: x[1])
for k, g in groupby(data, key=lambda x: x[1]):
    g = [x[0] for x in g]
    print(f'{k} = {g}')

Output:

Bombay = ['A', 'E']
Delhi = ['B']
Pune = ['C', 'D', 'F']

Here is another solution & storing in dict would be preferable over variable due to ease accessiblity.

result = {}

for c,p in zip(City, People):
    result.setdefault(c, []).append(p)

print(result)

{'Bombay': ['A', 'E'], 'Delhi': ['B'], 'Pune': ['C', 'D', 'F']}

You can use a dictionary

Dict = dict()

People = ["A","B","C","D","E","F"]
City = ["Bombay","Delhi","Pune","Pune","Bombay","Pune"]

for i in range (len (City)):
    if City[i] in Dict:
        Dict[City[i]].append (People[i])
    else:
        Dict[City[i]] = [ People[i] ]

for city in Dict:
    print (city, end = ': ')
    for people in Dict[city]:
        print (people, end = ' ')

    print()

This prints:

Bombay: A E 
Delhi: B 
Pune: C D F

Similarly, create another Dictionary for the tasks and assign a task as a value to every key (city) from the city_of Dictionary

How about that?

People = ["A","B","C","D","E","F"]
City = ["Bombay","Delhi","Pune","Pune","Bombay","Pune"]


data={}
for P in People:
    for C in City:
        data[P]=C

def X():
    print('do stuff X')
def Y():
    print('do stuff Y')
def Z():
    print('do stuff Z')
def A():
    print('do stuff A')

tasks={
    "Bombay":X(),
    "Delhi":Y(),
    "Pune":Z(),
    "Pune":A(),
    "Bombay":A(),
    "Pune":A()
}


for item in data:
    tasks[data[item]]

If you like one liners for maximum readability ;-) This list comprehension gets the unique cities and for every city name it gets the people in the zipped list that belong to this city:

people = ["A","B","C","D","E","F"]
cities = ["Bombay","Delhi","Pune","Pune","Bombay","Pune"]
    
result = [{city: [name[0]
 for name in list(zip(people, cities)) if name[1] == city]}
 for city in list(set(cities))]

print(result)

Output

[{'Pune': ['C', 'D', 'F']}, {'Bombay': ['A', 'E']}, {'Delhi': ['B']}]
Related