Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add a key to every object inside a list. #115

Open
rizwan29 opened this issue Oct 31, 2019 · 5 comments
Open

How to add a key to every object inside a list. #115

rizwan29 opened this issue Oct 31, 2019 · 5 comments

Comments

@rizwan29
Copy link

Eg. Input:

[ { "classA":"A1", "classB":"B1" }, { "classA":"A2", "classB":"B2" }, { "classA":"A3", "classB":"B3" } ]

Now I want to add a key classC to every object of the list and, the values for this key are coming from another variable.
Eg. values = ["C1", "C2", "C3"]

Output:
[ { "classA":"A1", "classB":"B1", "classC":"C1" }, { "classA":"A2", "classB":"B2", "classC":"C2" }, { "classA":"A3", "classB":"B3", "classC":"C3" } ]

@kurtbrose
Copy link
Collaborator

kurtbrose commented Nov 1, 2019

here's one way you could do it

glom( (object_list, c_list), (Invoke(zip).star(T), Assign(T[0]['classC'], T[1]), T[0]) )

@kurtbrose
Copy link
Collaborator

kurtbrose commented Nov 1, 2019

hmm this turned out to be embarrassingly complicated

>>> glom( (obj_list, c_list), (Invoke(zip).star(T), [(Assign(T[0]['classC'], Spec(T[1])), T[0])]) )
[{'classA': 'A1', 'classB': 'B1', 'classC': 'C1'}, {'classA': 'A2', 'classB': 'B2', 'classC': 'C2'}, 
{'classA': 'A3', 'classB': 'B3', 'classC': 'C3'}]

@kurtbrose
Copy link
Collaborator

(Invoke(zip).star(T), [(Assign(T[0]['classC'], T[1]), T[0])])

what can we do to clean this up?

  • Zip in reduction.py
  • Assign val eval Spec or T, not just Spec
(Zip(), [(Assign(T[0]['classC'], T[1]), T[0])])

@kurtbrose
Copy link
Collaborator

kurtbrose commented Nov 1, 2019

another approach...

(Invoke(zip).star(T), [(Let(class_c=T[1], T[0], Assign('classC', S['class_c'])])

@kurtbrose
Copy link
Collaborator

maybe another approach -- don't mutate the old but just move forward

also doesn't mutate the old

>>> glom( (obj_list, c_list), (Invoke(zip).star(T), [Invoke(dict).specs(T[0], classC=T[1])]) )
[{'classA': 'A1', 'classB': 'B1', 'classC': 'C1'}, {'classA': 'A2', 'classB': 'B2', 'classC': 'C2'}, 
{'classA': 'A3', 'classB': 'B3', 'classC': 'C3'}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants