Python ambiguous words

I have a color dictionary with several meanings:

dictcolors = {'Red': '1,2,3,4,5',
              'Green': '3,4,5',
              'Purple': '6',
              'Orange': '7', 
              'Blue': '1,2,3',
              'Teal': '3,4,5,6'}

How can you iterate over all values ​​and return the value and key (s) of which this value is part?

Result:
Value - Key(s)

1 - 'Red', 'Blue'
2 - 'Red', 'Blue'
3 - 'Red', 'Green', 'Blue', 'Teal'
4 - 'Red', 'Green', 'Teal'
5 - 'Red', 'Green', 'Teal'
6 - 'Purple', 'Teal'
7 - 'Orange'
+4
source share
2 answers

You can use defaultdict (available from py 2.6+) for this:

from collections import defaultdict
foundColors = defaultdict(set)
for key,value in dictcolors.iteritems():
    # Assuming the numbers are in a comma separated string
    for color in value.split(','):
        foundColors[color].add( key )

foundColors gives:

>>defaultdict(<type 'set'>, {'1': set(['Blue', 'Red']), '3': set(['Blue', 'Green', 'Red', 'Teal']), '2': set(['Blue', 'Red']), '5': set(['Green', 'Red', 'Teal']), '4': set(['Green', 'Red', 'Teal']), '7': set(['Orange']), '6': set(['Purple', 'Teal'])})

Another advantage of using it defaultdictis that it will not break when accessing numbers that do not exist in yours dictcolors. This is due to the fact that when accessing such keys, it initializes the key value with the empty type "default" (in this case set).

, - :

for number in range(10):
    print number,list(foundColors[number])
+7

- :

integer count = 0;
for key in dictcolors.keys():{
    print '{0}'.format( str(count) ) + ' - '
    if (dictcolors[key].find(str(count)))
        print key
-1

Source: https://habr.com/ru/post/1536809/


All Articles