在字典的值中找到列表的元素,并相应地以表格形式打印键



我有这个列表:

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

还有这本字典:

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

输出应该像:

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

因此,这里的目标是在字典的值中找到list1的元素,并打印相应的键。应采用表格形式,如图所示。

例如:列表中的float是字典中Keyword的一个关键字。

我真的没能为它设计一个循环!

您遇到了麻烦,因为您的字典是向后的。字典是用来查找映射到值的键的,而不是相反。所以首先转换你的字典:

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

现在的任务很琐碎:

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

我想你可以弄清楚如何在表格中打印页眉和页脚。

大量代码。对于漂亮的打印,For循环可能更可读。

# 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))

你可以做:

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})

最新更新