FutureB
FutureB

Reputation: 3

using multiple values of a key in a for loop

I am trying to modify a script that was using a pair of key:value in a for loop. I have to make changes to so the for loop can take 3 values for the key instead of just 1. Not sure how to go about it. Thanks in advance. I get this error:

for fileName,readPct,readhPct,writehPct in hpct_file_list.items():
    ...

ValueError: need more than 2 values to unpack

Here's is the code:

hpct_file_list = {'rhpct_50_80_20_tier2': ['80', '50', '0'], 'whpct_50_20_80_tier2': ['20', '0', '50']}

for fileName,readPct,readhPct,writehPct in hpct_file_list.items():
    hostRoot.VmExec("cd C:\\Program Files (x86)\\vdbench")
    VmCommon.LogMsg('Creating File : %s '%(fileName))
    hostRoot.VmExec("echo validate=yes > %s"%(fileName))
    hostRoot.VmExec("echo sd=sda, lun=%s, threads=16, hitarea=25m, size=875G >> %s" %(device_name, fileName))
    hostRoot.VmExec("echo wd=wd1, sd=sda, xfersize=512, rdpct=%s, rhpct=%s, whpct=%s, seekpct=random >> %s" % (readPct, readhPct, writehPct, fileName))
    hostRoot.VmExec("echo wd=wd2, sd=sda, xfersize=1k, rdpct=%s, rhpct=%s, whpct=%s, seekpct=random >> %s" % (readPct, readhPct, writehPct, fileName))

Upvotes: 0

Views: 95

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155438

items returns a list of two-tuples of the key and value, it doesn't flatten the value for you, so it can't be unpacked into four names at the same level. Python supports this though, you just add additional parentheses around the names that are to be unpacked from the subsequence:

for fileName, (readPct, readhPct, writehPct) in hpct_file_list.items():

This unpacks the key directly into fileName, while unpacking the value a second time (so the values must be length 3) to populate readPct, readhPct, writehPct.

Side-note: You might want to use iteritems rather than items to avoid a potentially large temporary list; iteritems will iterate the dict directly without making temporary large data structures.

Upvotes: 1

Related Questions