更改作为同一字典中的键的值:Python
Change value which is a key in the same dictionary: Python
输入:
oldNames = { 'Fruits':['orange', 'Banana', 'Peach', 'mango', 'raspberries']
'Meat': ['Bacon', 'Chicken', 'Ham', 'Steak']
'Food': ['Fruits', 'Rice', 'Beans', 'Meat'] }
示例代码:
oldNames = {} # Defining the dictionary I am creating from the file
newNames = {} # Defining another dictionary where I am planning to change the values
Keys_ = [] # Defining the list to append new values for new dictionary
Values_ = []
def dict_parse():
infiles = [f for f in os.listdir(path) if f.endswith('.pin')] # First few lines gets the match fromt he input file
for infile in infiles:
with open(path + '/' + infile, 'r') as inFile:
infileContents = inFile.read()
PATTERN = re.compile(r'Group (\w+)\s+([^\n]+)\s*\{(.*?)\}', re.DOTALL);
for match in PATTERN.finditer(infileContents):
keyname = match.group(1).strip()
elements = match.group(3).replace(',', '').split()
oldNames[keyname] = elements # I get the correct dictionary values until here.
for keyname, elements in oldNames.items(): # iterating over the keys and values of existing dict
for element in elements: # iterating over values
if (element in oldNames[keyname]): # condition to check if vlaue is a key
newNames = {}
for i in range(len(oldNames[keyname])):
Values_.append( oldNames[keyname][i]) # This part is wrong but not sure how to modify
newNames= dict((k,v) for k,v in (oldNames[keyname], Values_)) # This is not the correct format to form the dict I guess...
else:
newNames = dict((k,v) for k,v in oldNames[keyname])
print new_pinNames["Food"]
if __name__ =='__main__':
dict_parse()
我有值列表。我使用 for loop
遍历值列表,使用另一个 for loop
遍历匹配键的值。我需要将输出作为单个列表,其中替换了键的值,并且与之前的位置相同。发布示例输出以供参考。
我正在打印一个键,但我需要的是一本新字典,其中包含找到并替换的所有值。
预期输出:
['orange', 'Banana', 'Peach', 'mango', 'raspberries', 'Rice', 'Beans', 'Bacon', 'Chicken', 'Ham', 'Steak']
参考:
Used this : [This](
这会起作用...但是,当使用理解语法来实现如此复杂时,它肯定会让人感到困惑。
print dict(
[(key, [y for x in [[i] if i not in oldNames else oldNames[i]
for i in value] for y in x])
for key, value in oldNames.items()])
所以,您可以做的(如果对您来说太复杂的话)是这样写的:
newNames = {}
for key, value in oldNames.items():
valueLists = [[i] if i not in oldNames else oldNames[i] for i in value]
newNames[key] = []
for valueList in valueLists:
newNames[key].extend(valueList)
print newNames
说明:
本质上,第一个循环中的结果 valueLists
将如下所示:
# Using the 'Food' key
[['orange', 'Banana', 'Peach', 'mango', 'raspberries'], ['Rice'], ['Beans'], ['Bacon', 'Chicken', 'Ham', 'Steak']]
有意创建一个列表列表(即使是单个元素),以便以后可以统一展平(所有项目),而不关心某些项目是否确实没有任何嵌套键值(如 fruits
)。这使得添加或删除具有键值嵌套的项目变得容易,并且期望相同的行为一直有效。
# Here I iterate through valueLists, thus the first
# item in the loop would be (using the above example):
# ['orange', 'Banana', 'Peach', 'mango', 'raspberries']
for valueList in valueLists:
# Finally, the `extend` flattens it completely.
newNames[key].extend(valueList)
输出:
{'Food': ['orange', 'Banana', 'Peach', 'mango', 'raspberries', 'Rice', 'Beans', 'Bacon', 'Chicken', 'Ham', 'Steak'], 'Meat': ['Bacon', 'Chicken', 'Ham', 'Steak'], 'Fruits': ['orange', 'Banana', 'Peach', 'mango', 'raspberries']}
输入:
oldNames = { 'Fruits':['orange', 'Banana', 'Peach', 'mango', 'raspberries']
'Meat': ['Bacon', 'Chicken', 'Ham', 'Steak']
'Food': ['Fruits', 'Rice', 'Beans', 'Meat'] }
示例代码:
oldNames = {} # Defining the dictionary I am creating from the file
newNames = {} # Defining another dictionary where I am planning to change the values
Keys_ = [] # Defining the list to append new values for new dictionary
Values_ = []
def dict_parse():
infiles = [f for f in os.listdir(path) if f.endswith('.pin')] # First few lines gets the match fromt he input file
for infile in infiles:
with open(path + '/' + infile, 'r') as inFile:
infileContents = inFile.read()
PATTERN = re.compile(r'Group (\w+)\s+([^\n]+)\s*\{(.*?)\}', re.DOTALL);
for match in PATTERN.finditer(infileContents):
keyname = match.group(1).strip()
elements = match.group(3).replace(',', '').split()
oldNames[keyname] = elements # I get the correct dictionary values until here.
for keyname, elements in oldNames.items(): # iterating over the keys and values of existing dict
for element in elements: # iterating over values
if (element in oldNames[keyname]): # condition to check if vlaue is a key
newNames = {}
for i in range(len(oldNames[keyname])):
Values_.append( oldNames[keyname][i]) # This part is wrong but not sure how to modify
newNames= dict((k,v) for k,v in (oldNames[keyname], Values_)) # This is not the correct format to form the dict I guess...
else:
newNames = dict((k,v) for k,v in oldNames[keyname])
print new_pinNames["Food"]
if __name__ =='__main__':
dict_parse()
我有值列表。我使用 for loop
遍历值列表,使用另一个 for loop
遍历匹配键的值。我需要将输出作为单个列表,其中替换了键的值,并且与之前的位置相同。发布示例输出以供参考。
我正在打印一个键,但我需要的是一本新字典,其中包含找到并替换的所有值。
预期输出:
['orange', 'Banana', 'Peach', 'mango', 'raspberries', 'Rice', 'Beans', 'Bacon', 'Chicken', 'Ham', 'Steak']
参考:
Used this : [This](
这会起作用...但是,当使用理解语法来实现如此复杂时,它肯定会让人感到困惑。
print dict(
[(key, [y for x in [[i] if i not in oldNames else oldNames[i]
for i in value] for y in x])
for key, value in oldNames.items()])
所以,您可以做的(如果对您来说太复杂的话)是这样写的:
newNames = {}
for key, value in oldNames.items():
valueLists = [[i] if i not in oldNames else oldNames[i] for i in value]
newNames[key] = []
for valueList in valueLists:
newNames[key].extend(valueList)
print newNames
说明:
本质上,第一个循环中的结果 valueLists
将如下所示:
# Using the 'Food' key
[['orange', 'Banana', 'Peach', 'mango', 'raspberries'], ['Rice'], ['Beans'], ['Bacon', 'Chicken', 'Ham', 'Steak']]
有意创建一个列表列表(即使是单个元素),以便以后可以统一展平(所有项目),而不关心某些项目是否确实没有任何嵌套键值(如 fruits
)。这使得添加或删除具有键值嵌套的项目变得容易,并且期望相同的行为一直有效。
# Here I iterate through valueLists, thus the first
# item in the loop would be (using the above example):
# ['orange', 'Banana', 'Peach', 'mango', 'raspberries']
for valueList in valueLists:
# Finally, the `extend` flattens it completely.
newNames[key].extend(valueList)
输出:
{'Food': ['orange', 'Banana', 'Peach', 'mango', 'raspberries', 'Rice', 'Beans', 'Bacon', 'Chicken', 'Ham', 'Steak'], 'Meat': ['Bacon', 'Chicken', 'Ham', 'Steak'], 'Fruits': ['orange', 'Banana', 'Peach', 'mango', 'raspberries']}