0

I am trying to iterate over multiple object. How can i rewrite it using list comprehension?

for character in characters_rs:
    for item in mapping:
        if character.Get('NomId') == item.get('Номенклатура'):
            item['Attributes'] = character.Get('Attributes')

I tried something like aggregated_list = [character for character in characters_rs for item in mapping if character.Get('NomId') == item.get('Номенклатура') ] , but it's not what i expect.

mapping is a list, characters_rs is a custom RecordSet structure.

4
  • 3
    You don't seem to be building a list here, so you shouldn't use a list comprehension at all. Commented Oct 29, 2019 at 3:23
  • 1
    You cannot have an assignment statement in a list comprehension. Commented Oct 29, 2019 at 3:26
  • How is aggregated_list related to the first code snippet? Commented Oct 29, 2019 at 3:26
  • What type of data are character.Get('NomId') and item.get('Номенклатура') - are they integers, strings, something else? Commented Dec 9, 2019 at 20:43

1 Answer 1

1

You can swap the two loops since they are independent. That makes the process clearer: you want to update some of the items of the mapping iterable:

for item in mapping:
    for character in characters_rs:
        if character.Get('NomId') == item.get('Номенклатура'):
            item['Attributes'] = character.Get('Attributes')

More precisely, you update each item with the last character having character.Get('NomId') == item.get('Номенклатура'). Hence the list/dict comprehension that returns the updated version of mapping:

[{**{'Attributes': character.Get('Attributes')
     for character in characters_rs
     if character.Get('NomId') == item.get('Номенклатура')},
  **item}
 for item in mapping]

Explanation: {**d1, **d2} merges two dicts. Here, the first dict contains the last character having character.Get('NomId') == item.get('Номенклатура') mapped to Attributes (this dict may be empty), and the second is simply item itself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.