我从两个列表创建了一个字典。我正在尝试更新存储在字典中的值。我在for循环中使用if语句来过滤我想要修改的行,现在想要更改这些行的字典值。我想用字符串"Note Holder"来改变字典值到对应的姓" {family name} family。所以我想用new_names(the "blank")更新字典中的名称(Note Holder)。家庭)。下面是我的代码:
data = pd.read_excel('mailclean.xlsx')
ran = range(len(data))
tes = list(data.iloc[0:len(data)]['Column1'])
tes1 = list(data.iloc[0:len(data)]['Column2'])
dic = {}
for a in ran:
dic[tes[a]] = tes1[a]
for new_name in tes:
if "Family Trust" in new_name:
name = dic.get(new_name)
new_name = "The " + new_name[:-6]
print(new_name)
print(name)
下面是终端输出:
The Guerland Family
Note Holder
The Sciammas Family
Note Holder
The Hsu Family
Note Holder
The Hemingway Family
Note Holder
The Williams Family
Note Holder
The Svancara Family
Note Holder
The Schritter Family
Note Holder
The Meola Family
Note Holder
The Scipione Family
Note Holder
The Elmore Family
Note Holder
The Oeland Family
Note Holder
The Harmsen Family
Note Holder
The Mauger Family
Note Holder
The Hockema Family
Note Holder
The Vogl Family
Note Holder
The McKee Family
Note Holder
The Davis Family
Note Holder
The Katz Family
Note Holder
The Grewal Family
Note Holder
The Penner Family
Note Holder
The Johnson Family
Note Holder
The Johnson Family
Note Holder
The Johnson Family
Note Holder
The Nemeth Family
Note Holder
The Horan Family
Note Holder
The Quan Family
Note Holder
The Elliott Family
Note Holder
The Clay Family
Note Holder
The Edwards Family
Note Holder
The Smith Family
Note Holder
The Rau Family
Note Holder
The Barter Family
Note Holder
The Lyon Family
Note Holder
The Scheiber Family
Note Holder
The Betzing Family
Note Holder
The Porter Family
Note Holder
The Eller Family
Note Holder
The Sebring Family
Note Holder
我想用字符串"Note Holder"到对应的姓" {family name} family。所以我想用new_names(the "blank")更新字典中的名称(Note Holder)。家庭)。
好吧,照我写的,你把重要的信息都丢掉了。
for new_name in tes:
if "Family Trust" in new_name:
name = dic.get(new_name)
new_name = "The " + new_name[:-6]
print(new_name)
print(name)
new_name
变量是您在字典中所处位置的唯一锚,而您正在将其更改为其他内容,从而失去了您的位置。
改变持有键的变量没有任何意义。您想要更改存储在该键中的值,这只是另一个赋值,与您最初将值放在那里的赋值完全相同:
for name in dic:
if "Family Trust" in name:
dic[name] = "The " + name[:-6]
实际上,您可以首先通过修改创建字典的原始循环来完成:
for a in ran:
if "Family Trust" in tes[a]:
dic[tes[a]] = "The " + tes[a][:-6]
else:
dic[tes[a]] = tes1[a]
如果我理解正确的话,您首先创建了一个字典,其中键是数组tes
中的元素,值是相应数组索引中的tes1
。然后,在给定特定条件(您的if语句)的情况下,您希望将值(从tes1
)从Note Holder
更改为The {Family Name} Family
?
可能是这样的:
for name in tes:
if "Family Trust" in name:
new_name = "The " + name[:-6]
dict[new_name] = new_name
你可以像这样直接更新字典值,因为我理解你的问题。