![](/img/trans.png)
[英]How to iterate and append key value pairs from a dictionary within a dicionary and storing values with same key into a list python
[英]Issues adding values in dictionary when attempting to append key,value pairs
我試圖列出下游目錄,並在使用os.walk命令后按迭代順序為它們分配一個值。 問題是我在期望的結果后得到了一堆空的“ {}”值。
import os
path = "PATH\\TO\\DIRECTORY\\"
os.chdir(path)
for root, dirs, files in os.walk(path):
ij = 1
dir_output = {}
for dir in dirs:
dir_output[ij] = dir
ij += 1
print dir_output
我得到以下結果:
{'1': 'Value1', '2': 'Value2', '3': 'Value3'}
{}
{}
{}
我試圖擺脫那些空的“ {}”,但它似乎是特定於os.walk輸出的東西。 嘗試過.pop和.strip,但是遇到了錯誤。
通過將ij
和dir_output
的初始化dir_output
for循環之外,可以跳過其他空字典:
import os
path = "PATH\\TO\\DIRECTORY\\"
os.chdir(path)
dir_output = {}
ij = 1
for root, dirs, files in os.walk(path):
for dir_ in dirs:
dir_output[ij] = dir_
ij += 1
print dir_output
我試過了 它沒有按計划進行。
這是我解決的方法:
我沒有使用os.walk而是:
for dir in os.listdir('.'):
這樣,它只會遍歷目錄。 我不需要枚舉,因為我會將字典值映射到菜單上的選項中。 現在,最后一件事是將這些值映射為三行,而不是每行一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.