ragrets
ragrets

Reputation: 15

How to add a list from a for loop to each key in a dictionary?

I currently have a dictionary with channel ids as keys and a list full of video ids from channels in the dictionary which looks like this:

channel_ids = {
        'channel1_id': None, 
        'channel2_id': None
        }

set_of_video_ids = [
            'channel1_videoid1', 'channel1_videoid2', 
            'channel2_videoid1', 'channel2_videoid2'
            ]

My intention for this is to place each channel video id in a list and add it as a value for the key in the dictionary which should look like this

channel_ids = {
    'channel1_id': [
        'channel1_videoid1', 
        'channel1_videoid2'
        ] 
    'channel2_id': [
        'channel2_videoid1', 
        'channel2_videoid2'
        ]
    }

To attempt this, I have first split the set_of_video_ids list into two by creating a function and then added a for loop to put it as the value for each key.

for video_ids_per_channel in split_list(set_of_video_ids, number_of_parts = len(channel_ids.keys())):
    for channel_id in channel_ids.keys():
        channel_ids[channel_id] = video_ids_per_channel
        print(channel_ids)

Also, the video_ids_per_channel looked like this after the split:

['channel1_video1', 'channel1_video2']
['channel2_video1', 'channel2_video2']

However, when I am printing the dictionary to see the result, I get all possible combinations like this:

{
    'channel1': [
        'channel2_videoid1', 'channel2_videoid2'
    ], 
    'channel2': None
}

{
    'channel1': [
        'channel2_videoid1', 'channel2_videoid2
    ], 
    'channel2': [
        'channel2_videoid1', 'channel2_videoid2
    ]
}

{
    'channel1': [
        'channel2_videoid1', 'channel2_videoid2
    ], 
    'channel2': [
        'channel1_videoid1', 'channel1_videoid2
    ]
}

{
    'channel1': [
        'channel1_videoid1', 'channel1_videoid2
    ], 
    'channel2': [
        'channel1_videoid1', 'channel1_videoid2
    ]
}

How can i get this as a result?

{
    'channel1': [
        'channel1_videoid1', 'channel1_videoid2
    ], 
    'channel2': [
        'channel2_videoid1', 'channel2_videoid2
    ]
}

Upvotes: 0

Views: 171

Answers (2)

sub234
sub234

Reputation: 31

A combination of list comprehension and zip here. Assuming the names of the channel ids as channel1 and channel2.

vidlist = [[i for i in set_of_video_ids if j in i] for j in channel_ids]
mapped = zip(channel_ids,vidlist)
for k,r in mapped:
  channel_ids.update({k:r})

Upvotes: 1

AnsFourtyTwo
AnsFourtyTwo

Reputation: 2528

A list comprehension can do it:

for k in channel_ids.keys():
    channel_ids[k] = [v for v in set_of_video_ids if k.replace("_id","") in v]

I assume, that the keys of the dictonairy channel_ids without the ending "_id" are found as substring in the element of your array set_of_video_ids (which is actually no set, but a list!)

Upvotes: 0

Related Questions