rayray84 rayray84 - 1 year ago 103
Python Question

Python dict append is overwriting previous key:value

Firstly python 2.7.11

Overview, I'm gathering the directory names in a given path and passing them into a subprocess cmd. From that subprocess I'm iterating over the output line by line, the directory name is the key and the subprocess.stdout is the value.

What I need is to keep the key the same but save the unique values and add them to a dict so I can write to a csv later.

Snip it of code showing 2 methods I have already tried (one is commented out). Both overwrite the existing key:value in the dict.

data = []
for dname in listdir(path):
header = dname
if isfile:
entrydict = dict()
cmd = "ct lsh -fmt \"%u \\n\" -since 01-Oct-2015 -all " + dname
# output of cmd is "name \r\n"
p1 = subp.Popen(cmd, stdout=subp.PIPE, stderr=subp.PIPE)
usr = []
for name in iter(p1.stdout.readline, ''):
if name.rstrip() not in usr:
entrydict[header] = usr

for n in usr:
entrydict[header] = n


r44 r44
Answer Source

Yes, you could collect all of the unique values as a list like names = ['f0', 'f1', 'f2'] and then assign it to your dict with a header as a key like

entrydict[header] = names

Just make sure that all of header are different.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download