Home > Mobile >  Grouping items in lists based on keys
Grouping items in lists based on keys

Time:08-12

Given an iteratable with (key, value) pairs, return a dict with the keys and a list with all values for each specific key, including duplicates.

Example:

Input: [
    ('germany', 'john'), 
    ('finland', 'olavi'), 
    ('france', 'alice'), 
    ('germany', 'gerd'),
    ('germany', 'john')
]

Output: {
    'germany': ['john', 'gerd', 'john'], 
    'finland': ['olavi'], 
    'france': ['alice']
}

CodePudding user response:

This is just one of the many possible solutions.

input_data = [
    ('germany', 'john'), 
    ('finland', 'olavi'), 
    ('france', 'alice'), 
    ('germany', 'gerd'),
    ('germany', 'john')
]

output_data = {}
for k, v in input_data:
    output_data[k] = output_data.get(k, [])   [v]

CodePudding user response:

input_data=[
    ('germany', 'john'), 
    ('finland', 'olavi'), 
    ('france', 'alice'), 
    ('germany', 'gerd'),
    ('germany', 'john')
]
# Creating unique Keys with list as values
output={key:[] for key in dict.fromkeys([i[0] for i in input_data])}
# Fill the Lists with the correspondig Keys
for key,value in input_data:
    output[key].append(value)
print(output)

CodePudding user response:

Another variant:

given = [
    ('germany', 'john'), 
    ('finland', 'olavi'), 
    ('france', 'alice'), 
    ('germany', 'gerd'),
    ('germany', 'john')
]
    
result = dict()
for k, v in given:
    try:
        result[k].append(v)
    except KeyError:
        result[k] = [v]

CodePudding user response:

Hope it will usefull.

 input_data=[
        ('germany', 'john'), 
        ('finland', 'olavi'), 
        ('france', 'alice'), 
        ('germany', 'gerd'),
        ('germany', 'john')
    ]
    
    final_dict = {}
    key = []
    for inp in input:
        if inp[0] not in key:
           key.append(inp[0])
           final_dict[inp[0]] = [inp[1]]
        else:
            final_dict[inp[0]].append(inp[1])

CodePudding user response:

input_data = [
    ('germany', 'john'), 
    ('finland', 'olavi'), 
    ('france', 'alice'), 
    ('germany', 'gerd'),
    ('germany', 'john')
]

output_data = {}
for k, v in input_data:
    output_data[k] = output_data.get(k, [])   [v]

enter image description here

CodePudding user response:

Alternatively, you can try this - using dict.setdefault:


data= [
    ('germany', 'john'), 
    ('finland', 'olavi'), 
    ('france', 'alice'), 
    ('germany', 'gerd'),
    ('germany', 'john')
]

groups = {}

for country, name in data:
    groups.setdefault(country, []).append(name)

print(groups)

Output:

{'germany': ['john', 'gerd', 'john'], 'finland': ['olavi'], 'france': ['alice']}
  • Related