Home > Blockchain >  Ordering the values of a dictionary with a for loop iteration
Ordering the values of a dictionary with a for loop iteration

Time:09-08

I'm a Python Newb and trying to create a dictionary with ordered values.

Since dict.fromkeys only allows me to copy the same value for each key, I've set all values to 0 and tried something like this:

def Ord_Values_in_Dic(D):
    c = 0
    for value in D.values(): 
        c  = 1
        value  = c
        return D 

My output only changes the first value of the dictionary to 1 though, instead I'd want the second value to also change to 2, the third value to change to 3 and so on... I don't get if the loop isn't iterating correctly through the dictionary or there's something else wrong.

CodePudding user response:

Since dict.fromkeys only allows me to copy the same value for each key

then it is not right tool for you task. You might use zip to prepare dict from 2 iterables - one for keys, one for values, consider following simple example

keys = ["x","y","z"]
d = dict(zip(keys,range(3)))
print(d)  # {'x': 0, 'y': 1, 'z': 2}

range with single arguments gives subsequent numbers from 0 (inclusive) to given value (exclusive), so in above example: 0,1,2

CodePudding user response:

Got it!

import numpy as np

a = np.linspace(0,100,100)
b = np.sin(a)
c = np.cos(a)
idx = list(range(1,101))

X = dict(zip(b, idx))
Y = dict(zip(c, idx))

This solved it! Thank you :)

  • Related