You want to search for a string in a text file from a key in a dictionary to find the number of elements of value.

Asked 1 years ago, Updated 1 years ago, 223 views

As I am a beginner, there may be some strange points, but I appreciate your cooperation.

Text File Contents

AAA
BBB
CCC
DDD
Dictionary={
  US>'AAA': ['a', 'b', 'c',
  BBB: ['a', 'b', 'd', 'g',]
  'CCC': ['b', 'f',
  'DDD': ['b', 'c', 'f', 'g', 'h']
}

Text files and dictionaries are simplified.

The result is the number of elements per key.

3
4
2
5

I wrote the following script because I have no knowledge.However, I asked because I felt it was not versatile because I had to specify it manually.
Thank you for your cooperation.

Value=Dictionary.get('AAA')
print(len(value))

python

2023-01-11 17:24

1 Answers

dic={'AAA':['a', 'b', 'c', 'BBB':['a', 'b', 'd', 'g', 'CCC':['b', 'f', 'DDD':['b', 'c', 'f', 'g', 'h']}
with open('keys.txt', 'r') as f:
    for key inf:
        value = dic.get (key.rstrip(), None)
        if value is not None:
            print(len(value))
        
# 3
# 4
# 2
# 5


2023-01-11 18:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.