tech.77 r tech.77 r - 1 month ago 11
Python Question

How to write a function for dictionary from 2 lists in python with if condition?

How to write a function that takes a list of strings and a list of characters as arguments and returns a dictionary whose keys are the characters and whose values are lists of the strings that start with that character.

a_func(['apple','orange','banana','berry','corn'],['A','B','C'])


should give me

{'A':['apple'], 'B':['banana','berry'], 'C':['corn]}


I tried this but not sure how to put if condition in this,

a = ['apple','orange','banana','berry','corn']
b = ['A','B','C']
d = {}
for k,v in zip(b,a):
d.setdefault(k, []).append(v)
print (d)



---------
#output is
{'A': ['apple']}
{'A': ['apple'], 'B': ['orange']}
{'A': ['apple'], 'C': ['banana'], 'B': ['orange']}

Answer

What you are doing wrong with zip. This is what happens when you call zip the way you are doing it:

>>> list(zip(['A','B','C'], ['apple','orange','banana','berry','corn']))
[('A', 'apple'), ('B', 'orange'), ('C', 'banana')]

Which, as you can see, clearly does not match up to any helpful result you can use to get to your required output.

A much easier way to do this is to make use of defaultdict. Call your defaultdict with a list, so that the initial value of the dictionary entry will be a list. That way all you have to do is check the first character of each word against the character list using in. From there, just simply append once you find that your first character exists in your character list.

Also, you seem to have lower case words with an uppercase character list, so you should set the casing accordingly.


from collections import defaultdict


def a_func(words, chars):
    d = defaultdict(list)
    for word in words:
        upper_char = word[0].upper()
        if upper_char in chars:
            d[upper_char].append(word)
    return d


res = a_func(['apple','orange','banana','berry','corn'],['A','B','C'])

Result:

defaultdict(<class 'list'>, {'A': ['apple'], 'B': ['banana', 'berry'], 'C': ['corn']})
Comments