Home > Back-end >  Dictionary indexing in python?
Dictionary indexing in python?

Time:04-01

I have a dictionary in the following format: Key (string) : Value (list[string])

my_dict = {'Foo': ['Lorem', 'Ipsum', 'Dolor', 'Baz'], 'Bar': ['Amet', 'Consectetur'], 'Baz': ['...'], 'Lorem': ['...'], & so on...}

I want to access this dictionary by indexing each key, such that Foo = 1, Bar = 2, Baz = 3, Lorem = 4, Ipsum = 5.. and so on

I want to choose a key by index, then pick a value, and go to that index, and so on.

For example: If I pick 1, I will go to Foo. Then from Foo, I will go to either Lorem, Ipsum, Dolor, or Baz.

I am essentially creating another dictionary dict2, which will hold a number of integers as the new key, and the key from dict1 as its value.

First I tried to call dict2.update({int_list:dict1.keys()) but this resulted in an unhashable type error. Ok, so I converted the list into a tuple and it updated but did not result in the dictionary I wanted.

What is an appropriate way to go about doing this?

CodePudding user response:

Use enumerate() to pair each index with a key, then convert that to a dictionary:

dict2 = dict(enumerate(my_dict, 1))

CodePudding user response:

First you need to loop through the dic() with this

dic = dict()
for key, groups in my_dict.items():
    s = list(groups)
    print(f'{key}: {list(groups)}')
        for index , value in enumerate(s):
            second_item = value[
            total.append(second_item)
    print(dic)
  • Related