Home > database >  Is there anyway to save the value of a variable iterating through a list comprehension?
Is there anyway to save the value of a variable iterating through a list comprehension?

Time:12-06

Take this dictionary for example,

d = {
  1: ["a", "b"],
  2: ["c", "d"],
  3: ["e", 1]
}

What I want to do is something like this:

for i in d:
    if any(i in j for j in d.values()): # if a key of d exists in any of the lists 
        'add values of i to the list that had i in it'

So d would then look like:

d = {
  1: ["a", "b"],
  2: ["c", "d"],
  3: ["e", 1, "a", "b"]
}

I understand this can be simply done with a nested for loop, but is there any way with list comprehension?

CodePudding user response:

Yes, you can use a list comprehension to create a new list with the modified values, and then update the dictionary using this new list. Here is an example:

d = {
  1: ["a", "b"],
  2: ["c", "d"],
  3: ["e", 1]
}

# Create a new list with the modified values
new_values = [v   [d[i] for i in v if i in d] for k, v in d.items()]

# Update the dictionary with the new values
d = dict(zip(d.keys(), new_values))

# Output:
# {1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 1, 'a', 'b']}

Note that this will only work if the values in the dictionary are lists, and not if they are any other type of iterable. Also, this will modify the original dictionary. If you want to create a new dictionary without modifying the original, you can do this:

# Create a new dictionary with the modified values
d = {k: v   [d[i] for i in v if i in d] for k, v in d.items()}

Hope this helps

CodePudding user response:

I am not sure how to do this with a list comprehension, however,
this is how I would do it with nested for-loops:

Code:

d = {
  1: ["a", "b"],
  2: ["c", "d"],
  3: ["e", 1]
}

for k,v in d.items():
    for i in v:
        if i in d.keys():
            d[k] = d[k]   d[i]
            
print(d)

Output:

{1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 1, 'a', 'b']}

CodePudding user response:

Keep it simple. There may be a way to do this using a list comprehension but it would be highly esoteric and (potentially) hard to understand.

d = {
  1: ["a", "b"],
  2: ["c", "d"],
  3: ["e", 1]
}

for v in d.values():
    for e in v:
        if (_v := d.get(e)):
            v  = _v

print(d)

Output:

{1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 1, 'a', 'b']}
  • Related