简体   繁体   中英

Build a List of Tuples from a Dict

I have a list y of keys from a dictionary that is derived from a call to the Google Places API .

I would like to build a list of tuples for each point of interest:

lst = []
for i in range(len(y)):
    lst.append((y[i]['name'], y[i]['formatted_address'], y[i]['opening_hours']['open_now'], y[i]['rating']))

This works if the field is in the list and I receive a list of results that look like the one below, which is exactly what I want:

("Friedman's", '1187 Amsterdam Ave, New York, NY 10027, USA', True, 4.2)

However, the script throws an error if a desired field is not in the list y . How can I build a list of tuples that checks whether the desired field is in y before building the tuple?

Here's what I've tried:

    for i in range(len(y)):
        t = ()
        if y[i]['name']:
            t = t + lst.append(y[i]['name'])
        if y[i]['formatted_address']:
            t = t + lst.append(y[i]['formatted_address'])
        if y[i]['opening_hours']['open_now']:
            t = t + lst.append(y[i]['opening_hours']['open_now'])
        if y[i]['rating']:
            t = t + lst.append(y[i]['rating'])
    lst.append(t)

However, this doesn't work and seems very inelegant. Any suggestions?

For a start, you should almost never loop over range(len(something)). Always iterate over the thing directly. That goes a long way to making your code less inelegant.

For the actual issue, you could loop over the keys and only add the item if it is in the dict. That gets a bit more complicated with your one element that is a nested lookup, but if you take it out then your code just becomes:

for item in y:
    lst.append(tuple(item[key] for key in ('name', 'formatted_address', 'opening_hours', 'rating') if key in item))

This list comprehension uses default values when one of the keys is not present (using dict.get() ). I added variables so you can set the desired default values.

default_name = ''
default_address = ''
default_open_now = False
default_rating = 0.0

new_list = [
    (
        e.get('name', default_name),
        e.get('formatted_address', default_address),
        e.get('opening_hours', {}).get('open_now', default_open_now),
        e.get('rating', default_rating),
    )
    for e in y]

You can use the get feature from dict .

y[i].get('name')

if y[i] has key 'name' returns the value or None . For nested dicts, use default value from get .

y[i].get('opening_hours', {}).get('open_now')

For data structure, I recommend to keep it as an dict, and add dicts to an list.

lst = []
lst.append({'name': "Friedman's", "address": '1187 Amsterdam Ave, New York, NY 10027, USA'})

Try this:

for i in y:
    lst.append((v for k,v in i.items()))

you can use the keys method to find the keys in a dict. In your case:

lst=[]
fields = ('name', 'formatted_address', 'opening_hours' 'open_now', 'rating')
for i in range(len(y)):
    data = []
    for f in fields:
        if f in y[].keys():
            data.append(y[i][f])
        else:
            data.append(None)
    lst.append(set(data))

note that you can also get all the key, value pairs in a dict using the items() method. That would actually simply the code a bit. To make it even better, itterate over the set, rather than calling len(set) to:

lst=[]
fields = ('name', 'formatted_address', 'opening_hours' 'open_now', 'rating')
for i in y:
    data = []
        for key, value in i.items():
        if key in fields:
            data.append(value)
        else:
            data.append(None)
    lst.append(set(data))

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