如何将字典值附加到现有的字典值上?



假设我有一个:

dict = {"Main": ["Tammy","Elisha","Julius"],
"Elisha": ["Kenneth"]
}

上下文就像一个Queue系统。Main是普通队列。而"以利沙(Kenneth):"就像插队一样。你可以想象,当以利沙决定把他的朋友肯尼斯带进队伍时,每个人都在正常地排队买麦当劳。

如何添加"Kenneth"到"Main"Elisha"这样,当我打印dict['Main']时,它将返回以下预期的输出:

期望输出:[Tammy, Elisha, Kenneth, Julius ]

如果以利沙决定带另一个朋友来,"以利沙":["Nicole"]。那么预期的输出将是:

期望输出:[ Tammy, Elisha, Kenneth, Nicole, Julius ]

我试着用谷歌搜索append,但是append不能在字典中工作,只能在列表中工作。

我试着:

dict['Main'].value("Elisha").append("Kenneth")

但是返回错误。

可以递归地打印队列工作原理:

  1. 创建空队列
  2. Main队列第一个人开始
  3. 将该人员添加到1
  4. 中提到的空队列中
  5. 检查此人是否有朋友,如果有
  6. 将他们添加到1中提到的队列中,并检查他们的朋友是否存在
d = {"Main":["Tammy","Elisha","Julius"],
"Elisha": ["Kenneth"]
}
def get_flattened_queue(data, key, flattened_queue):
members = data[key]
for each_member in members:
flattened_queue.append(each_member)
if each_member in data.keys():
get_flattened_queue(data, each_member, flattened_queue)
return flattened_queue
flattened_queue = []
get_flattened_queue(d, 'Main', flattened_queue)
print(flattened_queue)
['Tammy', 'Elisha', 'Kenneth', 'Julius']

现在假设Elisa带来Nicole

d = {"Main":["Tammy","Elisha","Julius"],
"Elisha": ["Kenneth"]
}
def get_flattened_queue(data, key, flattened_queue):
members = data[key]
for each_member in members:
flattened_queue.append(each_member)
if each_member in data.keys():
get_flattened_queue(data, each_member, flattened_queue)
return flattened_queue
# Here she brings Nicole
d['Elisha'].append('Nicole')
#{"Main":["Tammy","Elisha","Julius"],
#        "Elisha": ["Kenneth", "Nicole"]
#       }
flattened_queue = []
get_flattened_queue(d, 'Main', flattened_queue)
print(flattened_queue)
['Tammy', 'Elisha', 'Kenneth', 'Nicole', 'Julius']

d = {"Main":["Tammy","Elisha","Julius"],
"Elisha": ["Kenneth"]
}
def get_flattened_queue(data, key, flattened_queue):
members = data[key]
for each_member in members:
flattened_queue.append(each_member)
if each_member in data.keys():
get_flattened_queue(data, each_member, flattened_queue)
return flattened_queue
# Here she brings Nicole
d['Elisha'].append('Nicole')
#{"Main":["Tammy","Elisha","Julius"],
#        "Elisha": ["Kenneth", "Nicole"]
#       }
# Nicole brings Epsi95
d['Nicole'] = ['Epsi95']
flattened_queue = []
get_flattened_queue(d, 'Main', flattened_queue)
print(flattened_queue)
{'Main': ['Tammy', 'Elisha', 'Julius'],
'Elisha': ['Kenneth', 'Nicole'],
'Nicole': ['Epsi95']}

['Tammy', 'Elisha', 'Kenneth', 'Nicole', 'Epsi95', 'Julius']

您需要为您的情况使用extend:

dic = {"Main":["Tammy","Elisha","Julius"],
"Elisha": ["Kenneth", "Nicole"]
}
dic["Main"].extend(dic["Elisha"])
print(dic["Main"])

输出:

['Tammy', 'Elisha', 'Julius', 'Kenneth', 'Nicole']

同时,避免在对象名称中使用关键字dict,以避免隐藏构建中的行为。

更新:

要在特定的index上插入,可以首先使用index()方法获得要插入的索引,然后使用切片方法插入新列表,如下:

idx = dic["Main"].index("Elisha")
dic["Main"][idx+1:len(dic["Elisha"])] = dic["Elisha"]
print(dic["Main"])
['Tammy', 'Elisha', 'Kenneth', 'Nicole', 'Julius']

相关内容

  • 没有找到相关文章