2015-02-07 216 views
1

輸入:變化值,它是在同一字典中的關鍵: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](http://stackoverflow.com/questions/3162166/python-looping-over-one-dictionary-and-creating-key-value-pairs-in-a-new-dictio) 

+0

你忘了逗號。 – 2015-02-07 02:02:26

回答

1

這將工作...但是,它可以使用理解語法時實現這種複雜性肯定會比較混亂。

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']] 

A清單列表(即使對於單個元素)是故意創建的,以便稍後可以統一平整(的所有項目中的),而不關心某些項目是否實際上沒有任何嵌套鍵值(如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']} 
+0

謝謝!它現在有效。我沒有像你所做的那樣列出清單,也無法產生最終結果,並感謝解釋。 – Doodle 2015-02-08 01:15:59

相關問題