Python: Split dictionary inside a list into multiple lists - python

I would like to split a string like this:
my_list = [{'lat': -27.239722222222223, 'name': 'Geraldton', 'long': 114.62222222222222}]
into individual values:
my_list2 = ['lat', -27.239,'name', 'Geraldton', 'long', 114.6222]
or into dictionary or list where I can call the elements to use.

You can use dict.items to get all tuples (key, value) in the dictionary, all that is left is to flatten them:
my_list = [{'lat': -27.239722222222223, 'name': 'Geraldton', 'long': 114.62222222222222}]
dictionary = my_list[0]
# flatten using list comprehension
flattened = [item for tup in dictionary.items() for item in tup]
Output:
['lat', -27.239722222222223, 'long', 114.62222222222222, 'name', 'Geraldton']

You could do something like this:
list1 = [{'lat': -27.239722222222223, 'name': 'Geraldton', 'long': 114.62222222222222}]
list2 = []
for key in list1[0]:
list2.append(key)
list2.append(list1[0][key])

Related

How to get dictionary value from key in a list?

I am trying to create a new list from a list of dictionary items.
Below is an example of 1 dictionary item.
{'id': 'bitcoin',
'symbol': 'btc',
'name': 'Bitcoin',
'current_price': 11907.43,
'market_cap': 220817187069,
'market_cap_rank': 1}
I want the list to just be of the id item. So what I am trying to achieve is a list with items {'bitcoin', 'etc', 'etc}
You can use list comprehension:
my_list = [{'id': 'bitcoin', 'symbol': 'btc', ...}, ...]
[d['id'] for d in my_list]
Which translates to : for each dictionary in my_list, extract the 'id' key.
id_list = [d["id"] for d in dictlist ]
This should work for you
list = [ i['id'] for i in list_of_dict]
this should help
Simple and readable code that solves the purpose:
main_list = []
for item in main_dict:
main_list.append(item.get("id", None))
print(main_list)

Convert a string to list of dictionaries

I have a string as below
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
If you see clearly its kind of 2 dictionaries
rule:unique,attribute:geo,name:unq1
and
rule:sum,attribute:sales,name:sum_sales
I want to convert them to as below
[
{'rule': 'sum', 'attribute': 'sales', 'name': 'sum_sales'},
{'rule': 'unique', 'attribute': 'geo', 'name': 'uniq1'}
]
Kindly help
I tried
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
dlist=[]
at_rule_gm=(x.split(':') for x in gmr.split(','))
dict(at_rule_gm)
but here I get only the last dictionary.
Start with sample of OP:
>>> gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
Make an empty list first.
>>> dlist = [ ]
Loop with entry over list, yielded by gmr.split(','),
Store entry.split(':') into pair,
Check whether first value in pair (the key) is 'rule'
If so, append a new empty dictionary to dlist
Store pair into last entry of dlist:
>>> for entry in gmr.split(','):
pair = entry.split(':')
if pair[0] == 'rule':
dlist.append({ })
dlist[-1][pair[0]] = pair[1]
Print result:
>>> print(dlist)
[{'name': 'unq1', 'attribute': 'geo', 'rule': 'unique'},
{'name': 'sum_sales', 'attribute': 'sales', 'rule': 'sum'}]
Looks like what OP intended to get.
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
split_str = gmr.split(',')
dlist = []
for num in range(0, len(split_str),3):
temp_dict = {}
temp1 = split_str[num]
temp2 = split_str[num+1]
temp3 = split_str[num+2]
key,value = temp1.split(':')
temp_dict.update({key:value})
key,value = temp2.split(':')
temp_dict.update({key:value})
key,value = temp3.split(':')
temp_dict.update({key:value})
dlist.append(temp_dict)
dict always gives a single dictionary, not a list of dictionaries. For the latter, you can use a list comprehension after first splitting by 'rule:':
gmr = 'rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
items = (f'rule:{x}' for x in filter(None, gmr.split('rule:')))
res = [dict(x.split(':') for x in item.split(',') if x) for item in items]
print(res)
# [{'attribute': 'geo', 'name': 'unq1', 'rule': 'unique'},
# {'attribute': 'sales', 'name': 'sum_sales', 'rule': 'sum'}]

Comparing the values inside a list with dictionary values inside the list

I have a dictionary inside a list :
list1 = [{'Value': 'John','Key': 'Name'},{'Value':'17','Key': 'Number'}]
And i have a list:
list2 = ['Name','Number']
How to check the values inside list2 are present in the list1.
If present i need to list the the Value.
Eg: If Name is present , print "John"
Please also read the comments:
for i in list2: #iterate through list2
for j in list1: #iterate through list of dictinaries
if i in j.values(): #if value of list2 present in the values of a dict then proceed
print(j['Value'])
You can use a for loop. Note I use set for list2 to enable O(1) lookup within your loop.
list1 = [{'Value': 'John','Key': 'Name'},{'Value':'17','Key': 'Number'}]
list2 = {'Name', 'Number'}
for item in list1:
if item['Key'] in list2:
print(item['Value'])
# John
# 17
Here is my one-line style suggestions easily readable IMHO.
First solution with result sorted in the same order as list1:
list1 = [{'Value': 'John','Key': 'Name'},{'Value':'17','Key': 'Number'}]
list2 = ['Name','Number']
values = [x['Value'] for x in list1 if x['Key'] in list2]
print(values)
# ['John', '17']
Second solution with result sorted in the same order as list2:
list1 = [{'Value': 'John','Key': 'Name'}, {'Value':'17','Key': 'Number'}]
list2 = ['Number', 'Name']
values = [x['Value'] for v in list2 for x in list1 if x['Key'] == v]
print(values)
# ['17', 'John']
First of all I would transform your list1 into its destiny: a dictionary.
dict1 = {d['Key']: d['Value'] for d in list1}
Then you can simply loop over list2 and print the value if the key is there:
for key in list2:
if key in dict1:
print(dict1[key])
This prints:
John
17

split dictionary into two lists , one list is for key, another list is for value

I want to split dictionary into two lists. one list is for key, another list is for value.
And it should be ordered as original
Original list:
[{"car":45845},{"house": 123}]
Expected result:
list1 = ["car", "house"]
list2 = [45845, 123]
fixed_list = [x.items() for x in list]
keys,values = zip(*fixed_list)
list1 = [k for item in [{"car":45845},{"house": 123}] for k,v in item.iteritems()]
list2 = [v for item in [{"car":45845},{"house": 123}] for k,v in item.iteritems()]
For Python 3 use dict.items() instead of dict.iteritems()
original = [{"car":45845},{"house": 123}]
a_dict = {}
for o in original:
a_dict.update(o)
print a_dict
print a_dict.keys()
print a_dict.values()
Output:
{'car': 45845, 'house': 123}
['car', 'house']
[45845, 123]
a =[{"car":45845},{"house": 123}]
list1 = [i.values()[0] for i in a] #iterate over values
list2= [i.keys()[0] for i in a] #iterate over keys

how to merge values of python dict in a list of dictionaries

i have a python list of dictionary as shown below:
mylist = [{'id':1,'value':4},{'id':1,'value':6},{'id':2,'value':6},{'id':3,'value':9},{'id':3,'value':56},{'id':3,'value':67},]
i am trying to create a new list of dictionaries like this by doing some operations on the above shown list of dictionaries
newlist = [{'id':1,'value':[4,6]},{'id':2,'value':[6]},{'id':3,'value':[9,56,67]}]
Does anyone know a good way to do this?
If list items are sorted by id, you can use itertools.groupby:
>>> mylist = [{'id':1,'value':4},{'id':1,'value':6},{'id':2,'value':6},{'id':3,'value':9},{'id':3,'value':56},{'id':3,'v alue':67},]
>>> import itertools
>>> [{'id': key, 'value': [x['value'] for x in grp]}
... for key, grp in itertools.groupby(mylist, key=lambda d: d['id'])]
[{'id': 1, 'value': [4, 6]},
{'id': 2, 'value': [6]},
{'id': 3, 'value': [9, 56, 67]}]
You can construct the entire the list of dictionaries as a single dictionary with multiple values, using defaultdict, like this
from collections import defaultdict
d = defaultdict(list)
for item in mylist:
d[item['id']].append(item['value'])
And then using list comprehension, you can reconstruct the required list of dictionaries like this
print[{'id': key, 'value': d[key]} for key in d]
# [{'id':1, 'value':[4, 6]}, {'id':2, 'value':[6]}, {'id':3, 'value':[9,56,67]}]
You could also use dict comprehension:
newlist = {key: [entries[key] for entries in diclist] for key, value in diclist[0].items()}

Categories