Вопрос

In python I wish to create a dictionary using a comprehension with keys that are strings, and values that are lists. What I cannot figure out, is how to append elements to these lists. For example consider my following attempt:

{c: [].append(x[0]) for x in g16.nodes(data=True) for c in colors if x[1]['color'] == c}

g16.nodes(data=True) gives a list of pairs where the first element is a string, and the second element is a dictionary which just specifies a color. As stated, I wish to make this structure into a dictionary, where the keys give the color, and the values are lists of strings which have this color.

If you have the solution, or if there is a better way to do this, please let me know!

Thanks for all the help.

Это было полезно?

Решение

You are trying to do this:

{c: [x[0] for x in g16.nodes(data=True) if x[1]['color'] == c] for c in colors}

But it's not very efficient as you are looping over g16.nodes(data=True) once for each color

Something like this is better

d = {c: [] for c in colors}
for x in g16.nodes(data=True):
    k = x[1]['color']
    if k in d:
        d[k].append(x[0])

If you know k is always in colors, you could simplify to

d = {c: [] for c in colors}
for x in g16.nodes(data=True):
    d[x[1]['color']].append(x[0])

Другие советы

Using a comprehension for a dictionary of key to lists is not going to be pretty. It's probably easier if you can try this:

Assuming g16.nodes(data=True) is something like

[('key1', {'color': 'black'}), ('key2', {'color': 'green')]

and the color key exists, you can try this:

from collections import defaultdict
gen = ((k, c['color']) for k, c in g16.nodes(data=True) if c['color'] in colors)
results = defaultdict(list)
for key, color in gen:
    results[color].append(key)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top