在字典中搜索键并获取值 - Python

Search key and get value in dictonary - Python

你好堆栈溢出,

我正在尝试将我保存在列表“root”中的值与字典中的键相匹配,这样我就可以得到这些值。但我不知道该怎么做。 :/ 也许有人对我有一些启发。非常感谢!

因此我创建了一个字典

import pandas as pd 

df=pd.read_excel(r'path').fillna("@Null$tring").sort_values(by=['VP'])

SP = df['SP'].tolist()
VP = df['VP'].tolist()
root = []

#sSP = set(SP)
#sVP = set(VP)

root = [i for i in SP if i not in VP]

#index =root.index

print(root)
#print(index(root))

d = dict (zip(SP,VP))



for key in d.keys():
    if key == root[0]:
        print(key)

(我没有足够的声誉来发表评论,所以我 post 我的评论作为答案,对此深表歉意)您的 for 循环仅将键与列表的第一个元素匹配。也许这可以帮助你? (我修正了我的缩进和 while 循环抱歉)

i = 0
while i <= len(d.keys()):
  
  for key in d.keys():
      if key == root[i]:
         print(key)
      i = i + 1

如果我正确理解了你的意图,你应该能够很好地利用 pandas.Index.difference and pandas.Series.isin

这是一个包含一些示例数据的示例:

import pandas as pd

# Sample data.
df1 = pd.DataFrame({
    "AP" : ["foobar", "foo",  "bar",  "baz",  "foobar"],
    "SP" : ["qux",    "spam", "qux",  "ham",  "qux"],
    "VP" : ["spam",   "ham",  "spam", "eggs", "eggs"]
})

# Identifies values in SP not present in VP.
root = pd.Index(df1["SP"]).difference(pd.Index(df1["VP"]))

# Masks out data where the value of SP is not present in root,
# then selects only the SP and VP columns from the resulting
# DataFrame and resets the index. 
df2 = df1[df1["SP"].isin(root)][["SP", "VP"]].reset_index(drop = True)

给定示例数据,在输出方面引导您完成每个步骤:

>>> df1
       AP    SP    VP
0  foobar   qux  spam
1     foo  spam   ham
2     bar   qux  spam
3     baz   ham  eggs
4  foobar   qux  eggs

root作为df1["SP"]df1["VP"]的区别,投射为pandas.Index对象:

>>> pd.Index(df1["SP"])
Index(['qux', 'spam', 'qux', 'ham', 'qux'], dtype='object', name='SP')

>>> pd.Index(df1["VP"])
Index(['spam', 'ham', 'spam', 'eggs', 'eggs'], dtype='object', name='VP')

>>> pd.Index(df1["SP"]).difference(pd.Index(df1["VP"]))
Index(['qux'], dtype='object')

然后我们检查 df["SP"] 的哪些值存在于 root 中,并使用结果布尔值 pandas.Series 作为 pandas.DataFrame:

的掩码
>>> df1["SP"].isin(root)
0     True
1    False
2     True
3    False
4     True
Name: SP, dtype: bool

>>> df1[df1["SP"].isin(root)]
       AP   SP    VP
0  foobar  qux  spam
2     bar  qux  spam
4  foobar  qux  eggs

最后,我们可以只索引我们感兴趣的两列并重置索引:

>>> df1[df1["SP"].isin(root)][["SP", "VP"]].reset_index(drop = True)
    SP    VP
0  qux  spam
1  qux  spam
2  qux  eggs