0

I have list=[gender,employment type] and i wanted to create a dictionary named gender and another dictionary named employment type. Can i name my dictionaries something as follows:

> list[0] = {key1: value}
> list[1] = {key2: value}

I wanted to name my dictionary arbitrarily depending on certain input.Is it possible to declare a dictionary using a string value from a list?

python novice
  • 379
  • 1
  • 4
  • 18

1 Answers1

0

You may want to look into a combination of map and enumerate. I've linked to the 2.x docs because of your tag, but I believe the functions are almost identical in 3.x.

Using a map:

>>> list=["gender", "employment type"]
>>> mapped=map(lambda x: {"key":x})
[{'key': 'gender'}, {'key': 'employment type'}]

with enumerate:

>>> list=["gender", "employment type"]
>>> map(lambda (i, x): {"key"+str(i):x}, enumerate(list))
[{'key0': 'gender'}, {'key1': 'employment type'}]

Given more deeply-nested structures — something like list=[[gender], [employment type]] — you can define a more intricate function as your mapper.

Alternatively, if you are looking at an array of [gender, employment type] tuples (something that more closely resembles [(gender, employment type)]) — you may want to look into "unzipping" the data. See the SO question: A Transpose/Unzip Function in Python (inverse of zip).

stites
  • 4,903
  • 5
  • 32
  • 43