Home > Back-end >  find the elements of a list in the values of a dictionary and accordingly print the key in tabular f
find the elements of a list in the values of a dictionary and accordingly print the key in tabular f

Time:01-21

I have this list:

list1 = ['float', 'x', 'b', 'a', '*', ' ', '=', '50'] 

and this dictionary:

combined_dict = {
    'Keyword': ['float', 'int', 'char'],
    'Identifier': ['x', 'b', 'a', 'p', 'n'],
    'Operator': ['*', ' ', '=', '-', '/'],
    'Constant': ['50', '100', '20']
}

The output should be like:

|list    | Type       |
|:------:|:----------:|
|float   | Keyword    |
| x      | Identifier |
| b      | Identifier |
| a      | Identifier |
| *      | Operator   |
|        | Operator   |
| =      | Operator   |
| 50     | Constant   |

So the goal here is to find the elements of list1 in the values of the dictionary and print the corresponding key. This should be in tabular form as shown.

eg : float from the list is a key of Keyword in the dictiornary.

I wasn't really able to design a loop for this!

CodePudding user response:

You're having trouble because your dictionary is backwards. Dictionaries are made to look up keys mapped to values, not the other way around. So transform your dictionary first:

lookup_dict = {v: k for k, vals in combined_dict.items() for v in vals}

Now the task is trivial:

for s in list1:
    print(f'| {s:06s} | {lookup_dict[s]:10s} |')

I think you can figure out how to print the header and footer in the table.

CodePudding user response:

you could do:

import pandas as pd
combined_dict={'Keyword': ['float','int','char'], 'Identifier': ['x', 'b', 'a','p','n'], 'Operator': ['*', ' ', '=','-','/'], 'Constant': ['50','100','20']}
list1=['float', 'x', 'b', 'a', '*', ' ', '=', '50'] 
types = []
for fromlistvalue in list1:
    for value in combined_dict:
        if fromlistvalue in combined_dict[value]:
            types.append(value)
df = pd.DataFrame({"list":list1,"Type":types})

CodePudding user response:

Lots of code. For the pretty-printing, a for loop might have been more readable.

# transform combined_dict, to allow lookup by token from list1
lookup = dict(sum((
    [(e, key) for e in value]
    for key, value in combined_dict.items()
), []))

# create list with tokens mapped to their corresponding type
mapped = [(key, lookup[key]) for key in list1]

# making it pretty

# column widths for the table based on longest cell in column
width_list = max((len(elem) for elem in list1))
width_type = max((len(t) for _, t in mapped))

# convert mapped tokens into printable rows
converted = ["|{}|{}|".format(
    i.ljust(width_list), t.ljust(width_type)) for i, t in mapped]

# prepare header and divider of table
header = "|{}|{}|".format(
    "list".ljust(width_list), "type".ljust(width_type))
divider = "| {} | {} |".format(
    "-" * (width_list - 2), "-" * (width_type - 2))

# merge all table lines into single string and print
print("\n".join([header, divider]   converted))
  •  Tags:  
  • Related