简体   繁体   中英

Python dict.get method apply some function on a key

Modified to make it more understandable.

I am testing out the python's dict.get method and need some help on that.

What I am trying to do is that I have a dictionary with some values. I am trying to copy that one value to another dictionary after applying a method on the value of the dictionary. here is how the code looks like

test_dict = {"name" : "test-12312", "phone" :"123456"}

result_dict = {}

result_dict['name'] = to_alphanumeric(test_dict.get('name', "Default-123"))

What I want to is that if the name exists in test_dict then apply to_alphanumeric function on it and store it in result_dict otherwise store the default value. The approach that I am following will also be applied on Default-123 if the value does not exists which I dont want. I want to apply the to_alphanumeric method only when the key test_dict['name'] exists.

What will be the best way to do that keeping in mind that Default value is in lower case and I only want to convert to upper case if value exists.

如果值不为空,则:

result_dict['name'] = test_dict.get('name', '').upper() or 'Default'

Try something like this

test_dict = defaultdict(lambda: 'default')
test_dict.get('name').capitalize()

or

test_dict = {}
test_dict.setfdefault('default')
test_dict.get('name').capitalize()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM