1

I have one dataset in a list form and I want to convert it into another dataset under certain conditions.

Conditions

  1. "a" = 1
  2. "b" = 2
  3. "c" = 3
input_list = ["a", "b", "c"]
#  something happens
output_list = [1, 2, 3]

What to do?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
alphonsos
  • 11
  • 1

2 Answers2

1
  1. Represent your set of conditions in a dictionary:
conditions = {
    "a": 1,
    "b": 2,
    "c": 3
}
  1. Use that dictionary in order to generate the output:
input_list = ["a", "b", "c"]
output_list = [conditions[x] for x in input_list]
  • How do you do the _conversion_ or _mapping_ with this dictionary? Please explain the concepts (e.g. key-value, map function, list comprehension). – hc_dev Jul 03 '22 at 20:11
0

What you want to achieve is a mapping.

Your conditions are a map, dictionary (Python lingo) or hash-table. Each value there (like 1) corresponds to a key in the dataset (like "a").

To represent this mapping you can use a table-like datastructure that maps a key to a value. In Python this datastructure is called a dictionary:

mapping = {"a": 1, "b": 2, "c": 3}  # used to translate from key to value (e.g. "a" to 1)

input_list = ["a", "b", "c"]

#  something happens
output_list = []
for v in input_list:
    mapped_value = mapping[v]  # get the corresponding value, translate or map it
    print(v + " -> " + mapped_value)
    output_list.append(mapped_value)

print(output_list)  # [1, 2, 3]

See also

hc_dev
  • 8,389
  • 1
  • 26
  • 38