Convert a string key to int in a Dictionary

前端 未结 3 1970
我寻月下人不归
我寻月下人不归 2020-12-08 06:55

My question is very similar to this one, except I have a dictionary of lists and I\'m interested in changing both the key value and all elements in every list form str

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 07:15

    d = {'1':'145' , '2':'254' , '3':'43'}
    d = {int(k):int(v) for k,v in d.items()}
    >>> d
    {1: 145, 2: 254, 3: 43}
    

    for lists in values

    >>> d = { '1':['1', '2', '3', '4'] , '2':['1', '4'] , '3':['43','176'] }
    >>> d = {int(k):[int(i) for i in v] for k,v in d.items()}
    

    in your case:

    coautorshipDictionary = {int(k):int(v) for k,v in json.load(json_data)}
    

    or

    coautorshipDictionary = {
        int(k):[int(i) for i in v] for k,v in json.load(json_data)}
    

提交回复
热议问题