I have a excel sheet i.e,
我有一张excel表格,
0 first |second |third |root
1 credible |credulous |credibility|cred
2 cryptogram|cryptology|cryptic |crypt
3 aquatic |aquarium |aqueduct |aqua
i want to import key and value for dictionary from above mentioned excel sheet:
for example: i have written a dictionary code for storing this values
我想从上面提到的excel表中导入关键字和值,例如:我编写了一个用于存储这些值的字典代码。
new_dict = {
('credible','credulous','credibility') : 'cred',
('cryptogram','cryptology','cryptic') : 'crypt'
}
so instead of writing key and value for each word in dictionary i want to import from excel where first 3 column(i.e first,second,third) should be the key and last column(i.e root) will be the value of a dictionary. Is it possible to do that?
sorry for my English.
Thanks
因此,我不需要为字典中的每个词编写键和值,而是要从excel中导入,其中第一列为i。e first、second、third应该是键和最后一列(i)。e根)将是字典的值。有可能吗?对不起,我的英语。谢谢
2 个解决方案
#1
1
Use set_index
to set the index for every column (first three, in this case) besides the root
, and then call root.to_dict
:
使用set_index为除根外的每一列(本例中为前三列)设置索引,然后调用root.to_dict:
df.set_index(df.columns.difference(['root']).tolist()).root.to_dict()
{
('aquatic', 'aquarium', 'aqueduct') : 'aqua',
('credible', 'credulous', 'credibility') : 'cred',
('cryptogram', 'cryptology', 'cryptic') : 'crypt'
}
#2
1
Use set_index
by first 3 columns with Series.to_dict
:
使用set_index前3列包含Series.to_dict:
d = df.set_index(['first','second','third'])['root'].to_dict()
print (d)
{('credible', 'credulous', 'credibility'): 'cred',
('aquatic', 'aquarium', 'aqueduct'): 'aqua',
('cryptogram', 'cryptology', 'cryptic'): 'crypt'}
#1
1
Use set_index
to set the index for every column (first three, in this case) besides the root
, and then call root.to_dict
:
使用set_index为除根外的每一列(本例中为前三列)设置索引,然后调用root.to_dict:
df.set_index(df.columns.difference(['root']).tolist()).root.to_dict()
{
('aquatic', 'aquarium', 'aqueduct') : 'aqua',
('credible', 'credulous', 'credibility') : 'cred',
('cryptogram', 'cryptology', 'cryptic') : 'crypt'
}
#2
1
Use set_index
by first 3 columns with Series.to_dict
:
使用set_index前3列包含Series.to_dict:
d = df.set_index(['first','second','third'])['root'].to_dict()
print (d)
{('credible', 'credulous', 'credibility'): 'cred',
('aquatic', 'aquarium', 'aqueduct'): 'aqua',
('cryptogram', 'cryptology', 'cryptic'): 'crypt'}