Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

How to create sub dictionaries out of a large dictionary in Python?

I have a Python dictionary like below. In which you can see some values are all zeros for a given key. I want to create sub-dictionaries out of the main dictionary whenever it contains non-zero values.

74: (0, 0, 0, 0, 0),
 75: (0, 0, 0, 0, 0),
 76: (0, 0, 0, 0, 0),
 77: (69, 76, 151, 157, 42),
 78: (68, 78, 150, 160, 100),
 79: (69, 77, 151, 159, 64),
 80: (69, 77, 151, 159, 64),
 81: (71, 74, 154, 158, 12),
 82: (0, 0, 0, 0, 0),
 83: (0, 0, 0, 0, 0),
 84: (0, 0, 0, 0, 0),
 85: (0, 0, 0, 0, 0),
 86: (0, 0, 0, 0, 0),
 87: (0, 0, 0, 0, 0),
 88: (0, 0, 0, 0, 0),
 89: (0, 0, 0, 0, 0),
 90: (0, 0, 0, 0, 0),
 91: (0, 0, 0, 0, 0),
 92: (0, 0, 0, 0, 0),
 93: (0, 0, 0, 0, 0),
 94: (0, 0, 0, 0, 0),
 95: (64, 68, 150, 153, 12),
 96: (63, 79, 148, 159, 176),
 97: (64, 79, 148, 159, 165),
 98: (63, 81, 146, 175, 522),
 99: (63, 82, 145, 179, 646),

For example, in the above case, I should be able to create two sub-dictionaries (from 77-81 & 95-99). How can I achieve this in Python?

question from:https://stackoverflow.com/questions/65863152/how-to-create-sub-dictionaries-out-of-a-large-dictionary-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a dict comprehension with a condition:

output = {key: value for key, value in orig_dict.items() if all(value)}

If you want to be more explicit:

output = {key: value for key, value in orig_dict.items() if all(n != 0 for n in value)}

In both cases, output is

{77: (69, 76, 151, 157, 42),
 78: (68, 78, 150, 160, 100),
 79: (69, 77, 151, 159, 64),
 80: (69, 77, 151, 159, 64),
 81: (71, 74, 154, 158, 12),
 95: (64, 68, 150, 153, 12),
 96: (63, 79, 148, 159, 176),
 97: (64, 79, 148, 159, 165),
 98: (63, 81, 146, 175, 522),
 99: (63, 82, 145, 179, 646)}

The above example will add an entry to the new dictionary if and only if all the numbers in the tuple are non-zero. If you want to add the entry if any number is non-zero, change all to any.

If you want 2 (or more) dictionaries, use a loop with extra conditions:

a = {}
b = {}
for key, value in orig_dict.items():
    if all(value):
        if key in range(77, 82):
            a[key] = value
        elif key in range(95, 100):
            b[key] = value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...