0

I would like to know what is the most elegant or pythonic way to copy specific values from one dictionary into another, only if the values are not None, empty, or empty dict. The new dictionary will have different key names than the original one.

For example, let's assume I got a response from API and I converted json to dict

customer = [{
 'name': 'John',
 'email': 'johnsmith@gmail.com',
 'phoneNumber': '9999999',
 'country': 'USA',
 'city': None,
 'preferences': {}
}]

new_customer_dict = {}

for client in customer:
  
  if client.get('name'):
    new_customer_dict ['customer_name'] = client['name']

  if client.get('email'):
    new_customer_dict['customer_email'] = client['email']

Andrew
  • 1,507
  • 1
  • 22
  • 42
  • 2
    A simple way is to create a translation dict which maps original key names to new names, and then have a generic loop to filter and translate based on the key's presence in the translation table. – sj95126 Sep 11 '21 at 14:08

1 Answers1

2

How about something like this:

>>> customer_keys = [k for client in customer for k in client.keys()]
>>> customer_keys
['city', 'name', 'phoneNumber', 'email', 'country', 'preferences']
>>> new_customer_dict = {'customer_{}'.format(k): client.get(k)
...                       for client in customer 
...                             for k in customer_keys 
...                                 if client.get(k) is not None 
...                                     and client.get(k)}
>>> new_customer_dict
{'customer_name': 'John', 'customer_phoneNumber': '9999999', 'customer_country': 'USA', 'customer_email': 'johnsmith@gmail.com'}

Basically, first, you make a list of all the keys you want to look for. Next, you iterate over the list while making sure that value (of dict) is not None. You also check if the value (of dict) is not None.

Hope you got the idea!

ravi
  • 6,140
  • 18
  • 77
  • 154
  • 1
    This approach still feels too rigid. Prefixing the key with ```customer_``` was part of the example given, but it may not be the case that every key is modified exactly that way. Having a dictionary that specifies the translations would be more flexible. – sj95126 Sep 11 '21 at 14:23
  • @sj95126: That totally depends on OP's intention. As you said, the `customer_keys` can be modified as a `dict` (instead of `list`) to mention the mapping. – ravi Sep 11 '21 at 14:29
  • 1
    Thank you very interesting approach, yes customer prefix will not be always the same, but i guess I can just use `k` as my key – Andrew Sep 11 '21 at 14:37
  • @Andrew: As I said earlier, you can modify the `customer_keys` from `list` to `dict` and mention your mapping. However, the easiest solution is to get rid of the `customer_` prefix completely. Finally, if this answers your query, please accept the answer by clicking on check mark! – ravi Sep 11 '21 at 14:41