简体   繁体   中英

Inserting dict objects from a list with key-value pairs to a new list

I have a dict called data , it has one key called clubs that maps to a list which contains dict objects. I would like to add every object from the clubs list to a new list .

I could loop through the list and create a new one, however the arr contains only the key names of the dict object. How can I add the whole dict objects to my new list, not just the key names? Basically I want the list that is inside the clubs dict.

This is how my arr list looks:

['key1', 'key2', 'key1', 'key2', 'key1', 'key2', 'key1', key2]

And here is my implementation:

arr = []

for item in data['clubs']:

    arr.extend(item)

print (len(arr))

print (arr)    

I don't understand why I get just strings (key names), In Objective-c it would work.( data['clubs'] would be a list , item is a dict obj from the list that I add to a new list called arr . )

And here is how the raw (json) data looks:

{ "clubs": [
    {
        "location": "Dallas",
        "id": "013325K52",
        "type": "bar"
    },

    {
        "location": "Dallas",
        "id": "763825X56",
        "type": "restaurant"
    }
] }

And I would like something like this:

{
    "location": "Dallas",
    "id": "013325K52",
    "type": "bar"
},

{
    "location": "Dallas",
    "id": "763825X56",
    "type": "restaurant"
}

arr.extend(item) will try to interpret item as a sequence , and add all the items in that sequence to arr . To add a single element, use append .

arr = []
for item in data['clubs']:
    arr.append(item)
print(arr)

However, you could just write:

print(list(data['clubs']))

Your JSON is already a key/value pair where the value is a python list . To extract this in to its own list, you simply assign from the key:

arr = data['clubs']   # returns the list associated with this key!

An alternative which may be more useful if you need to do any additional processing of the items in the list/dict:

arr = [{}]* len(data['clubs'])
for k, v in enumerate(data['clubs']):
    arr[k] = v

print(arr)

Should result with:

[
{'type': 'bar', 
  'location': 'Dallas', 
  'id': '013325K52'}, 
 {'type': 'restaurant', 
  'location': 'Dallas', 
  'id': '763825X56'}
]

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