1

I have changed dic 1 to dic 2 to find the common vales between the the same keys. it is cleaned and I removed one number at the end in dic 1. I wrote the function as follows to find the common features that is called common.

My final output should looks like as follows keeping the original format of common values, but I dont know how to implement it:

from functools import reduce

dic1 = {"df1":["age_0" , "nnn220","abc70"], "df2":["age_1" "a221","abc71"]} 

dic2 = {"df1":["age","nnn22","abc7"], "df2":["age", "a22","abc7"]} 

dataframe_list = list(dic2.values())
common = reduce(lambda a, b: set(a) & set(b), dataframe_list)



common = {'AGE',
 'abc7'}

final_output :{"df1":["age0", "abc70"], "df2":["age1","abc71"]} 
ella
  • 201
  • 6
  • Does this answer your question? [How to get the difference between two dictionaries in Python?](https://stackoverflow.com/questions/32815640/how-to-get-the-difference-between-two-dictionaries-in-python) – JonSG Apr 24 '23 at 15:55
  • Welcome to Stack Overflow! Please take the [tour]. SO is a Q&A site, but this is not a question. What do you need help with exactly? Why should that output come from that input? Like, what's the algorithm? For more tips, please read [ask]. You might also want to read [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/q/284236/4518341) – wjandrea Apr 24 '23 at 15:58
  • No it doesn't ! – ella Apr 24 '23 at 15:59

1 Answers1

2

There's no need to use reduce to get your common values, just use set.intersection:

common = set.intersection(*map(set, dic2.values()))

As for filtering dic1 you can use re and a comprehenesion like this:

is_common = re.compile("|".join(common)).match
result = {k: [e for e in v if is_common(e)] for k, v in dic1.items()}

Result:

{'df1': ['age_0', 'abc70'], 'df2': ['age_1a221', 'abc71']}
Jab
  • 26,853
  • 21
  • 75
  • 114
  • 1
    FYI, looks like you're missing a comma in dic1 between `age_1` and `a221` that's why the second list looks the way it does. – Jab Apr 24 '23 at 16:07
  • Thanks, what does "|" is doing here ? why we can not use "," – ella Apr 24 '23 at 20:03
  • And also what does * is doing – ella Apr 24 '23 at 20:16
  • @ella The `*` unpacks the values from `map` so the sets are supplied instead of the `map` of sets. And the `|` is the delimiter because it means `or` in regex. – Jab Apr 25 '23 at 12:24