简体   繁体   中英

How can I replace all the values of a Python dictionary with a range of values?

I have the following dictionary:

mydict = {('a', 'b'): 28.379,
          ('c', 'd'): 32.292,
          ('e', 'f'): 61.295,
          ('g', 'h'): 112.593,
          ('i', 'j'): 117.975}

And I would like to replace all the values with a range from 1 to 5, but keep the order of the keys. As a result, I would get this:

mydict = {('a', 'b'): 1,
          ('c', 'd'): 2,
          ('e', 'f'): 3,
          ('g', 'h'): 4,
          ('i', 'j'): 5}

The length of the dictionary is actually 22000, so I need a range from 1 to 22000. How can I do it?

Thanks in advance.

Using enumerate to iterate on the keys, you can do:

mydict = {('a', 'b'): 28.379,
          ('c', 'd'): 32.292,
          ('e', 'f'): 61.295,
          ('g', 'h'): 112.593,
          ('i', 'j'): 117.975}

for i, key in enumerate(mydict):  # iterates on the keys
    mydict[key] = i


print(mydict)
# {('a', 'b'): 0, ('c', 'd'): 1, ('e', 'f'): 2, ('g', 'h'): 3, ('i', 'j'): 4}

Important note: dicts are only officially ordered since Python 3.7 (and in the CPython implementation since 3.6), so this would n't make much sense with older versions of Python.


To answer your comment: enumerate takes an optional second parameter start (that defaults to 0)

So, if you want to start at 1, just do:

for i, key in enumerate(mydict, start=1):  # iterates on the keys
    mydict[key] = i

The most simple is to create another dictionary from the keys of the previous one.

mydict2=dict()
for i,key in enumerate(mydict):
    mydict2[key]=i+1

You can do this with a one-liner which is more compact:

mydict = {('a', 'b'): 28.379,
          ('c', 'd'): 32.292,
          ('e', 'f'): 61.295,
          ('g', 'h'): 112.593,
          ('i', 'j'): 117.975}

{k: i for i, (k, v) in enumerate(mydict.items())}

Pandas solution for this:

import pandas as pd
a = pd.DataFrame(mydict, index=[0]).T
a[0] = list(range(0,len(a)))
a.to_dict()[0]

#  {('a', 'b'): 0, ('c', 'd'): 1, ('e', 'f'): 2, ('g', 'h'): 3, ('i', 'j'): 4}

This can be done gracefully with dict.update and itertools.count , and explicit loops can be avoided:

>>> mydict = {('a', 'b'): 28.379,
...           ('c', 'd'): 32.292,
...           ('e', 'f'): 61.295,
...           ('g', 'h'): 112.593,
...           ('i', 'j'): 117.975}
>>> from itertools import count
>>> mydict.update(zip(mydict, count(1)))
>>> mydict
{('a', 'b'): 1, ('c', 'd'): 2, ('e', 'f'): 3, ('g', 'h'): 4, ('i', 'j'): 5}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM