Question

In order to make CSV files with many columns, I have many, many instances of

try:
  printlist.append(text['data'])
except:
  printlist.append('')

Is it possible to condense these 4 lines into 1 or 2 (mostly for easier reading of the code)? I've tried with this function but I haven't discovered a way to pass something that doesn't exist.

def tryexcept(input):
    try:
        printlist.append(input)
    except:
        printlist.append('')

    return printlist

UPDATE I should mention that 'text' is actually a dict value, so it should look like

printlist.append(text['data'])

(changed above)

Était-ce utile?

La solution

What about:

printlist.append(text['data'] if 'data' in text else '')

Or even better as @bruno desthuilliers suggested:

printlist.append(text.get('data',''))

[EDIT]

For nested dict I normally use my dict selector:

class TokenDataType:
    LIST = "list"
    DICT = "dict"

def _select_key(keyitt, data):
    try:
        new_key = keyitt.next()
    except StopIteration:
        return data
    if new_key["t"] == TokenDataType.DICT:
        return _select_key(keyitt, data[new_key["k"]])
    elif new_key["t"] == TokenDataType.LIST:
        return _select_key(keyitt, data[new_key["i"]])

def tokenize_query(query):
    tokens = []
    for token in query.split("."):
        token = token.strip()
        if token:
            ttype = TokenDataType.LIST if "[" in token else TokenDataType.DICT
            if ttype == TokenDataType.LIST:
                index = None
                if len(token) >= 3:
                    index = int(token.replace("[", "").replace("]", ""))
                tokens.append({"k":token, "t":ttype, "i":index})
            else:
                tokens.append({"k":token, "t":ttype})
    return tokens

def normalize_query(query=None, tokens=None):
    if tokens == None:
        tokens = tokenize_query(query)
    return ".".join([token["k"] for token in tokens])

def select(query, data, throw_exception_on_key_not_found=False):
    tokens = tokenize_query(query)
    try:
        return _select_key(iter(tokens), data)
    except Exception as e:
        if throw_exception_on_key_not_found:
            raise e
        return None

DQ = select

if __name__ == "__main__":
    test = {"bla":1, "foo":{"bar":2}, "baz":[{"x":1}, {"x":2}]}
    print(DQ(".bla", test))
    print(DQ("bla", test))
    print(DQ("nothere", test))
    print(DQ(".foo", test))
    print(DQ("foo.bar", test))
    print(DQ("baz", test))
    print(DQ("baz.[0]", test))
    print(DQ("baz.[1].x", test))
    print(DQ("baz.[2].x", test))

for your case (appends None when one of the keys is not found):

printlist.append(DQ("data.someotherkey.yetanotherkey", text))

Autres conseils

There's a dictionary method that does exactly this, and it let's you specify any default value.

input = text.get('data', default='')

printlist.append(input)

It checks if the key exists in the dictionary, and if not, it returns the default value. More on dictionaries here.

Try this simple wrapper:

def execute_with_exception_handling(f):
    try:
        return f()
    except:
        raise

Then you execute your function:

def my_func():
    return 0 / 0

execute_with_exception_handling(my_func)

You can also add arguments to the function with *args. And you can even use decorators...that you can google because I recall off the top of my head how that works.

Why do you need to pass something that does not exist?

You can simply call function if the value that is being passed in is not "None" (Or any other unwanted value).

tryexcept( x ) if x is not None else None

Edit: Are you are trying to see if the variable is declared or not? If yes, one way to get around this would be to declare the variable beforehand:

x = None
...
tryexcept( x ) if x is not None else None
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top