Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

compare list values with dictionories python

I have a list and dictionary

   lis = ["abc","bcd fg","cda"]
   dic = {1:"dcbagh",2:"cd abc", 3:"fg"}

I want to compare the list values with a dictionary values and return a new dictionary like below,

res_dic = {1:"none" ,2:"abc" , 3:"bcd fg"}

We need to return a corresponding string even if matches slightly. I have tried with the following method. But nothing worked out.

n = {}
for k,v in dic.items():
    for i in lis:
        if i==k:
            n[k] = v

this is another method

n = {k: d[k] for k in d.keys() & set(lis)}
question from:https://stackoverflow.com/questions/65863973/compare-list-values-with-dictionories-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your condition is wrong. if i == k compares the list element with the dictionary key, but you want to compare with the value, which is v. And you don't need an exact match, you're looking for a substring, so you should be using in rather than ==. Since you seem to allow either string to be a substring of the other, use if v in i or i in v:

And the value you assign in the result is supposed to be the list element, not the dictionary value.

But you also want to use the value "none" if no match is found. So you need to break out of the loop when you find a match, and use else: to assign a value if the loop completes without breaking.

n = {}
for k,v in dic.items():
    for i in lis:
        if v in i or i in v:
            n[k] = i
            break
    else:
        n[k] = "none"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...