Home > Net >  Iterate over dictionary to get specific key's count
Iterate over dictionary to get specific key's count

Time:02-22

I am just a beginner in coding, trying to self teach python, then I got a lot of questions in my mind. so consider I have a main.py with a function def catch_urls(**kwargs): I will pass key:value arguments while running the file. My requirement here is there will be a bunch of arguments I pass to the function of which I need to find out the count of pattern matching keys- that means

main.py type=internal url1=google.com url2=yahoo.com timeout=10s url3=stackoverflow.com

Q1. How to get the count of how many url1, url2, url3, .... is given in arguments ? these url* count will vary on each runs then how to get the count of this pattern keys ? can we do something like psuedo code like count(url*)

Q2. Using **kwargs can I actually get these arguments passed into execution ? or do I need to use some library called "click" or so to get these arguments passed into my function ?

CodePudding user response:

The arguments arrive as strings in sys.argv. So, given your example, sys.argv would be a list containing:

[
    "main.py",
    "type=internal",
    "url1=google.com",
    "url2=yahoo.com",
    "timeout=10s",
    "url3=stackoverflow,.com"
]

You can parse those yourself, or you can use the argparse module to parse them.

It's not usually productive to spent a lot of time optimizing code that only gets used once. You could certainly say:

    cnt = sum(i.startswith("url") for i in sys.argv)

**kwargs is used for functions within a program. It's not involved in command line arguments.

  • Related