Home > Enterprise >  Reverse dictionary attributes set to ids?
Reverse dictionary attributes set to ids?

Time:01-06

I have the following translation dictionary:

{0: {'a', 'b', 'c'},
1: {'a', 'b', 'c', 'd'},
2: {'k', 'b', 'e', 'a', 'n'}}

And I want to 'reverse' it to be attributes to keys (keys here are a form of id). Given a set of attributes, give me the relevant id (key).

For example, given {'a', 'b', 'c'} return 0.

What is the best practice to do this? The attributes can come in different order that's why I am using sets. Should I insert it into a dataframe (translation table)? Or there is another solution?

CodePudding user response:

Not sure why you want to use pandas. Here is a pure python solution.

You can reverse the dictionary to use a frozenset as key:

d = {0: {'a', 'b', 'c'},
     1: {'a', 'b', 'c', 'd'},
     2: {'k', 'b', 'e', 'a', 'n'}}

rev_d = {frozenset(k): v for v,k in d.items()}

rev_d[frozenset({'a', 'c', 'b'})]
# 0

CodePudding user response:

you can use a Series to achieve this in pandas:

import pandas as pd

x = {0: {'a', 'b', 'c'},
1: {'a', 'b', 'c', 'd'},
2: {'k', 'b', 'e', 'a', 'n'}}

lookup = pd.Series(x)
print(lookup[lookup.values == {'a', 'b', 'c'}])
# 0    {c, b, a}
# dtype: object

CodePudding user response:

You could just walk through your entire dict and look for matches like so:

def att_to_key(d: dict, attributes: dict) -> int:
    for k,v in d.items():
        if v == attributes:
            return k

If your then do the following with d being your original dict and attributes being the attribute dict you want to look for

f = att_to_key(d, {"a","b","c"})
print(f)

it outputs your 0

  •  Tags:  
  • Related