简体   繁体   中英

Is it possible in a dict?- creating a dict and adding each key by increment

I'm trying to take some selective values from a dict which is inside another dict.

new_list = {}

for x in name_list:
    y =name_list[x]
    num =0  
    for key, value in y.items():
        if value == 'a_given_string_from_key':
            print(name_list[x])
            num= num+1
            new_list.update(num ,name_list[x])

But it looks not possible. How to resolve this?

Input:

name_list = {
      1 : {'_name' :'gilchrist','Team_name' : 'australia'},
      2 : {'_name' :'dhoni','Team_name' : 'india'},
      3 : {'_name' :'prior','Team_name' : 'england'},
      4 : {'_name' :'rishab','Team_name' : 'india'}, 
      5 : {'_name' :'rahul','Team_name' : 'india'}                           
 }

Expected otput:

new_list = {
      1 : {'_name' :'dhoni','Team_name' : 'india'},
      2 : {'_name' :'rishab','Team_name' : 'india'}, 
      3 : {'_name' :'rahul','Team_name' : 'india'} 
      }

I need those new_list keys incrementally.

If you just replace

new_list.update(num ,name_list[x])

by

new_list[num] = name_list[x]

this seems to do what you want.

The update method can be used to change multiple items in a dictionary at once, by taking them from another dictionary.

But you simply want to insert one item at a time into the dictionary.


The name new_list and the fact that you want to use incrementing integers as keys suggests that you actually want new_list to be a list, not a dictionary. You would change the code to this:

new_list = []

for y in name_list.values():
    for value in y.values():
        if value == 'a_given_string_from_key':
            new_list.append(y)
            break

The result should be something like

new_list = [
    {'_name' :'dhoni','Team_name' : 'india'},
    {'_name' :'rishab','Team_name' : 'india'}, 
    {'_name' :'rahul','Team_name' : 'india'} 
]

# new_list[0] --> {'_name' :'dhoni','Team_name' : 'india'}
# new_list[1] --> {'_name' :'rishab','Team_name' : 'india'}
# etc.

I've made some other small improvements which I'll leave for you to figure out.

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