tech.77 r tech.77 r - 1 year ago 62
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.


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 Source

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:
    return d

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


defaultdict(<class 'list'>, {'A': ['apple'], 'B': ['banana', 'berry'], 'C': ['corn']})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download