bupersadweenie
bupersadweenie

Reputation: 13

How to create function using list *args to a dictionary?

Hi I'm trying to write a function that takes a variable number of lists that can contain any number of words. What I am hoping to return is a dictionary where the words are the keys and the values are the total count of each word in all of the lists.

My code works with a single list:

wl1 = ['double', 'triple', 'int', 'quadruple']
new_dict = {}
for i in range(len(wl1)):
    new_dict[wl1[i]] = wl1.count(wl1[i])

and returns this:

{'double': 1, 'triple': 1, 'int': 1, 'quadruple': 1}

But it doesn't work with multiple lists and shows an unhashable list type:

def varlist(*items):
    newdict = {}
    for i in range(len(items)):
        newdict[items[i]] = items.count(items[i])
    return (newdict)

Should I be using **kwargs instead to make it into a dictionary? And if so, would I change variable list items into a dictionary using their frequency count? Any tips would be super helpful.

Upvotes: 1

Views: 137

Answers (2)

Brad Martsberger
Brad Martsberger

Reputation: 1967

You can take your variable number of lists and turn them into one list:

def varlist(*items):
    items = itertools.chain(*items)
    return dict(Counter(items))

Upvotes: 1

soloidx
soloidx

Reputation: 749

Based on the code you have, the problem is located at this line:

             newdict[items[i]] = items.count(items[I])

I tested the function and I passed a couple of list (['foo', 'bar'], ['foo','bad']), the problem is that the items variable now contains a list of lists:

[['foo', 'bar'], ['foo','bad']]

so, when you make the first for and try to put inside newdict you are doing something like this:

newdict[['foo','bar']] = ....

since you cannot use a list as a key for a dictionary you got the "unhashable list type"

what you can do is to merge all the lists into a single master list:

master_list = [word for sublist in items for word in sublist]

this is the modified version:

def varlist(*items):
    newdict = {}
    master_list = [word for sublist in items for word in sublist]
    for i in range(len(master_list)):
        newdict[master_list[i]] = master_list.count(master_list[i])
    return newdict

Upvotes: 1

Related Questions