Convert specific items in a dictionary to lists

A Score Level 1

Given a dictionary D , and a list of nodes N, I need to replace all existing nodes in the dictionary which are single value to list of values containing the single one.

For example:
   D= {foo:"bar",bar:"baz"}, N={"foo"} => {foo:{"bar"} /*converted*/,bar:"baz"/*no change*/}

   D={bar:"baz",foo:{"multi","items"},nested:{foo:"bar"}}, N={"foo","bar"} => {bar:{"baz"} /*converted*/,foo:{"multi","items"}/*no change*/ ,nested:{foo:{"bar"} /*converted*/}

The use case is to support conversion from XML where certain nodes should be arrays, however when converting from XML to JSON and there is 

a single item under those nodes, we need it to be array and not a single object. 

  Discussion posts and replies are publicly visible

Parents
  • You can resolve this by using a combination of custom scripting and the built-in "map" function.

    1. First, you can define a custom function that takes a dictionary and a list of nodes as input and returns a new dictionary with the desired changes.

    2. The custom function should iterate over the keys of the input dictionary and check if each key is in the list of nodes to be converted.

    3. If a key is in the list, and its value is not already a list, wrap it in a list with a single element.

    4. If the value is already a list, leave it as is.

    5. After making the necessary conversions, return the modified dictionary.

    6. Finally, use the built-in "map" function to apply the custom function to each element in the list of dictionaries.

Reply
  • You can resolve this by using a combination of custom scripting and the built-in "map" function.

    1. First, you can define a custom function that takes a dictionary and a list of nodes as input and returns a new dictionary with the desired changes.

    2. The custom function should iterate over the keys of the input dictionary and check if each key is in the list of nodes to be converted.

    3. If a key is in the list, and its value is not already a list, wrap it in a list with a single element.

    4. If the value is already a list, leave it as is.

    5. After making the necessary conversions, return the modified dictionary.

    6. Finally, use the built-in "map" function to apply the custom function to each element in the list of dictionaries.

Children
No Data