feedthemachine
feedthemachine

Reputation: 620

Assign value to key in a loop

I have a dictionary with keys in it but no values:

> {'GROUP': '?', 'THREAD': '?', 'SEQUENCE': '?', 'BYTES': '?', 'BLOCKSIZE': '?'}

I do also have a loop which returns lists of values:

for row in rng:
    result = [d[row] for d in inp]
    print(result)
> ['1', '2', '3']
> ['1', '1', '1']
> ['346', '347', '348']
> ['52428800', '52428800', '52428800']
> ['512', '512', '512']

How could I assign the db.keys to db.values, so the output looks like this:

{'GROUP': ['1', '2', '3'], THREAD': ['1', '1', '1'], 'SEQUENCE': ['1', '1', '1'], 'BYTES': ['52428800', '52428800', '52428800'], etc.}

Should I do values assignment in the loop directly?

Upvotes: 3

Views: 13352

Answers (3)

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

To follow with the input structure you've shared in question, you can use dict comprehension. That is,

{k:result[index] for index, k in enumerate(yourdict.keys())}

yourdict is the dictionary that you've given in your question.

Another solution is by following Markus answer.

dict(zip(yourdict.keys(),result)

Hope this helps!

Upvotes: -1

Mahi
Mahi

Reputation: 21913

Since dictionaries are unordered (the keys you've defined are in random order, regardless of which order you define them in), there's no way to know which result list you want to assign to which key.

What I would do instead is create a list or a tuple of the keys to keep the order:

keys = ('GROUP', 'THREAD', 'SEQUENCE', 'BYTES', 'BLOCKSIZE')

Then fetch all the values into another list (or better yet, a generator):

values = ([d[row] for d in inp] for row in rng)

So now you have two iterables in the same order, one with keys and one with corresponding values. Here's what they'd look like as lists (values is a generator so we can't really print the values):

>>> print(keys)
['GROUP', 'THREAD', 'SEQUENCE', 'BYTES', 'BLOCKSIZE']
>>> print(values)
[['1', '2', '3'], ['1', '1', '1'], ['346', '347', '348'], ['52428800', '52428800', '52428800'], ['512', '512', '512']]

Now it's easy to construct the final result dictionary with the built-in zip() function:

data = dict(zip(keys, values))

Upvotes: 2

timgeb
timgeb

Reputation: 78690

If the order of keys you want assign to is fixed, then build an iterator that spits out the keynames in whatever order you want.

keynames = iter(['GROUP', 'THREAD', 'SEQUENCE', 'BYTES', ...])

for row in rng:
    # your code
    ...

    # new code
    key = next(keynames)
    d[key] = result

If you want to assign to the key row in each iteration, just do it:

for row in rng:
    # your code
    ...

    # new code
    d[row] = result

(Assuming d is your dictionary you want to assign to, change as needed.)

Upvotes: 0

Related Questions