how to merge two lists with duplacated factors into a dict in python? [duplicate]

85
April 13, 2022, at 10:40 PM
This question already has answers here:
Merge two dictionaries and keep the values for duplicate keys in Python (8 answers)
Closed 2 months ago.

I know there's a way to merge lists into a dict by zip function, but once the 'key-list' contains duplicated factors it doesn't works well since many values will be cut. I wonder if there is a good solution to merge lists with the same keys?

assume we have two lists below, one is to be key and another is to be value

    list_k = [1,1,2]
    list_v = [3,6,9]

if I apply zip as usual, we will get following result

    dict = {k:v for k, v in zip(list_k, list_v)}
    #{1:3, 2:9}

however, what I want is as below

    #dict = {1:[3,6],2:[9]}
Answer 1

You could use collections.defaultdict:

from collections import defaultdict
list_k = [1, 1, 2]
list_v = [3, 6, 9]
merged = defaultdict(list)
for k, v in zip(list_k, list_v):
    merged[k].append(v)
merged = dict(merged)
print(merged)

Output:

{1: [3, 6], 2: [9]}
Rent Charter Buses Company
READ ALSO
Tkinter Button Command switches when new Button is used [duplicate]

Tkinter Button Command switches when new Button is used [duplicate]

I face an issue which is that my first button is using the second button's commandI have faced this logic error multiple times when trying to create buttons programmatically with different functions, is there a way to resolve this or is this a limitation...

139
Updating a node with merge using Py2Neo

Updating a node with merge using Py2Neo

I'm trying to merge and then update a graph using the py2neo libraryMy code looks roughly like

93
Replacing numerical IDs contained as lists of strings and lists of ints in a Pandas DataFrame

Replacing numerical IDs contained as lists of strings and lists of ints in a Pandas DataFrame

In order to make data anonymous, I need to replace original IDs with a different set of new IDs, but still have identical original IDs match across all fields after being replacedThe challenge is doing so elegantly across 4 different presentations of IDs in this Pandas...

130
How to compress pandas dataframe

How to compress pandas dataframe

Below I am showing few entries of my dataframeMy (each) dataframe has millions row

126