无他,唯手熟尔!

Process the string “k:1 |k1:2|k2:3|k3:4” into a dictionary {k:1,k1:2,…}

str1 = "k:1|k1:2|k2:3|k3:4"
def str2dict(str1):
    dict1 = {}
    for iterms in str1.split('|'):
        key,value = iterms.split(':')
        dict1[key] = value
    return dict1
#Dictionary derivation 
#d = {key:value for (key,value) in iterable}
d = {k:int(v) for t in str1.split("|") for k, v in (t.split(":"), )}

2,Please sort the age of the elements in alist by big to small

alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}]
def sort_by_age(list1):
    return sorted(alist,key=lambda x:x['age'],reverse=True)
赞(0) 打赏
未经允许不得转载:沙の志 » Process the string “k:1 |k1:2|k2:3|k3:4” into a dictionary {k:1,k1:2,…}

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

沙の志