Dict Practice Question - I ( DS150423 ) - 12-05-2023

Write a function that takes a list of dictionaries as input and returns a dictionary where the keys are unique names from the list of dictionaries, and the values are lists of dictionaries that contain the corresponding name.

Sample Input :

 [
    {'name': 'John', 'age': 25},
    {'name': 'Alice', 'age': 30},
    {'name': 'John', 'age': 35},
    {'name': 'Bob', 'age': 40}
]

Sample Output :

{
    'John': [{'name': 'John', 'age': 25}, {'name': 'John', 'age': 35}],
    'Alice': [{'name': 'Alice', 'age': 30}],
    'Bob': [{'name': 'Bob', 'age': 40}]
}
1 Like
def get_user_info():
    name = input("Enter a name: ")
    age = input("Enter an age: ")
    return {'name': name, 'age': age}

def group_by_names(users):
    result = {}
    for user in users:
        name = user.get('name')
        if name:
            if name not in result:
                result[name] = [user]
            else:
                result[name].append(user)
    return result  

# Example usage:
users = []
for i in range(3):
    users.append(get_user_info())
print(group_by_names(users))def get_user_info():
    name = input("Enter a name: ")
    age = input("Enter an age: ")
    return {'name': name, 'age': age}

def group_by_names(users):
    result = {}
    for user in users:
        name = user.get('name')
        if name:
            if name not in result:
                result[name] = [user]
            else:
                result[name].append(user)
    return result  

# Example usage:
users = []
for i in range(3):
    users.append(get_user_info())
print(group_by_names(users))

1 Like

Mam Solution Please

I have applied like 6 loops and still it doesn’t work

def group_by_name(lst):
    result = {}
    for d in lst:
        name = d['name']
        if name in result:
            result[name].append(d)
        else:
            result[name] = [d]
    return result

sample_input = [
    {'name': 'John', 'age': 25},
    {'name': 'Alice', 'age': 30},
    {'name': 'John', 'age': 35},
    {'name': 'Bob', 'age': 40}
]

print(group_by_name(sample_input))


{
    'John': [{'name': 'John', 'age': 25}, {'name': 'John', 'age': 35}],
    'Alice': [{'name': 'Alice', 'age': 30}],
    'Bob': [{'name': 'Bob', 'age': 40}]
}
1 Like

@007swarajbari

You asked me a question yesterday on session.
But I didn’t get the question here on community portal.
Can you please paste it here , so that I can clear your doubts?