I have a list of values that I am trying to match with a column of a pandas df and then would like to create a dictionary that will have list values as keys and then dictionary values from a different column from the data frame.
This is how I have my list:
sample_list = [101,105,112]
My Data Frame:
sample_df = pd.DataFrame([[101, "NJ"], [105, "CA"],[111, "MO"], [101, "NJ"], [112, "NB"], [101, "NJ"], [105, "CA"]], \
columns=["Col1", "Col2"])
looks like this,
Col1 Col2
0 101 NJ
1 105 CA
2 111 MO
3 101 NJ
4 112 NB
5 101 NJ
6 105 CA
Now, I am trying to iterate list values (which are keys of my new_dict)and match them with Col1 and if they match I would like to extract Col2 values as my dictionary values. This is how I have my code so far,
new_dict = {}
for value in sample_list:
for i in sample_df['Col1']:
if value == i:
new_dict[value] = [i for i in sample_df['Col2']]
However, my new_dict looks like this,
{101: ['NJ', 'CA', 'MO', 'NJ', 'NB', 'NJ', 'CA'],
105: ['NJ', 'CA', 'MO', 'NJ', 'NB', 'NJ', 'CA'],
112: ['NJ', 'CA', 'MO', 'NJ', 'NB', 'NJ', 'CA']}
I need my output like this,
{101: ['NJ'],
105: ['CA'],
112: ['NB']}
How can I get to my desired output? Any help would be nice.
new_dictto be lists?