grouping values in a list of tuples to a dictionary I've a list of tuples (comes in pairs only)

a = [(1,2),(1,4),(3,5),(5,7)]


which I'm trying to convert to a dictionary as below

d = {1: [2, 4], 3: 5, 5: 7}


Here's what I've come up with - 

a= [(1,2),(1,4),(3,5),(5,7)]
d= {}

for k, v in a:
    if k not in d:
        d[k] = v
    else:
        d[k] = [d[k]]
        d[k].append(v)


Is there a better way to do this? Can this be achieved using something like defaultdict(list) without having to compromise on the desired output?
I can't think of a builtin that solves your problem, but there is an even simpler solution than the one you provided. Taking Gareth Rees' comment into consideration, I would solve your problem like this:

input_list = [(1,2),(1,4),(3,5),(5,7)]
output_dict = {}

for key, value in input_list:
    #Initialize empty list if key doesn't exist
    if key not in output_dict:
        output_dict[key] = []
    # Now we know that the key always exists
    output_dict[key].append(value)

print(output_dict)
# If you want single items to be integers instead of lists
for key, value in output_dict.items():
    if len(value) == 1:
        output_dict[key] = value[0]

print(output_dict)


Output:

{1: [2, 4], 3: [5], 5: [7]}
{1: [2, 4], 3: 5, 5: 7}


The first for loop creates a dictionary mapping ints to lists. The advantages of this structure compared to the solution you provided is that there are no type-checks required when parsing the data. Checking if a value is a duplicate is a simple if len(value) &gt; 1. 

Usually, I'd prefer this implementation in any application that is not extremely dependent on performance. If your application requires a lot of performance, I'd suggest:


Not using Python
Not using dicts


If this is the case, I could elaborate on more ways of improving performance. 

In the more likely scenario that a coherent data structure is more important, I'd reduce your code to the first for-loop above, and wrapping it in a function: 

def list_to_dict(input_list):
    output_dict = {}
    for key, value in input_list:
        if key not in output_dict:
            output_dict[key] = []
        output_dict[key].append(value)
    return output_dict