2

I'm trying to create a dictionary that gets keys from one dictionary as key, and gets numbers from range() as values. For example, this is what I've tried;

files = {'/var/www/test.jgp': 40kb, '/var/www/banner.jgp':40kb}
files_num = dict((key, value) for key in files.keys() for value in range(1, len(files) + 1))

Which didn't work. I know this can be done if I create a list of the files.keys() and a list of range(1, len(files) + 1) and then use something like zip. But was wondering if there was a more elegant solution using dict comprehensions.

I'm looking for the output to be something like this:

{'/var/www/test.jgp': 1, '/var/www/banner.jgp': 2}

Any advice on this (assuming it is possible to do with dict comprehension) would be appreciated).

user1165419
  • 663
  • 2
  • 10
  • 21
  • Are you trying to make the value of each key stand for some sort of index or something? I'm confused about what you're trying to do. – Tagc Jan 26 '17 at 19:39

1 Answers1

3

You could make use of enumerate() with a starting index:

>>> {f: n for n, f in enumerate(files, 1)}
{'/var/www/test.jgp': 1, '/var/www/banner.jgp': 2}

Just bear in mind that dict objects are inherently unordered. That's obviously fine if you just want the keys numbered in some unspecified order. If, however, you are expecting some particular ordering, you might need a rethink (or collections.OrderedDict).

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012