i have list
li = ['Peter', '22', 'DE']
and i want to create json from this list so i need to add to every parameter in list a name, so outpur will be something like this
li = ['name':'Peter', 'age':'22', 'nationality':'DE']
i = 0
while i < len(li):
li[i].insert(0,'name:')
i += 1
print(li)
this adding to every added name a coma...how can i add to this list without comma?
because output from this is :
['name','Peter', '22', 'DE']
li is the list object which you are iterating over so any operations on that will act as operations performed over the list.
insert() will insert elements in the existing list.
You can use zip() with dict() after creating the keys for the dictionary to get the desired output:
li = ['Peter', '22', 'DE']
keys = ['name', 'age', 'nationality']
di = dict(zip(keys, li))
Update: You can use list comprehension for list of lists:
li = [ ['Peter', '22', 'DE'], ['John', '28', 'GB'] ]
keys = ['name', 'age', 'nationality']
di = [dict(zip(keys, l)) for l in li]
print(di)
You could use zip, to combine all values of both lists and convert it to a dict:
li = ['Peter', '22', 'DE']
keys = ['name', 'age', 'nationality']
print(dict(zip(keys, li)))
Out:
{'name': 'Peter', 'age': '22', 'nationality': 'DE'}
Generate Keys and then map those keys with value present in the list to create a dictionary convert dictionary to JSON
ky = ['Name', 'Age', 'Nationality']
li = ['Peter', '22', 'DE']
data = {k:v for (k,v) in zip(ky, li)}
What you need is not a list, but a dictionary. Dictionaries are collections paired with keys and values:
my_dict = {"name" : "Peter", "age" : 22, "nationality" : "DE"}
If you need to build a dictionary over a list, you can do it with zip() method:
li = ['Peter', '22', 'DE']
keys = ["name", 'age', 'nationality']
dictionary = dict(zip(keys, li)) # {'name': 'Peter', 'age': '22', 'nationality': 'DE'}
If you really need to work with JSON files, then i suggest looking into this link for a clear explanation.
Related
I have a list of names of unknown length. I want to write the names with their corresponding key (name to an empty list of dictionaries).
Input:
names = ['john', 'bill']
Output:
[{'name': 'john'}, {'name': 'bill'}]
Here it is:
names = ['john', 'bill']
dic = [{'name': name} for name in names]
print(dic)
#[{'name': 'john'}, {'name': 'bill'}]
I have a nested dictionary:
d = { 'wing': {'name': 'Ali', 'age': '19'},
'scrumHalf': {'name': 'Bob', 'age': '25'},
'flyHalf': {'name': 'Sam', 'age': '43'},
'prop': {'name': 'rob', 'age': '33'}}
I want to pull out the values for age only to generate a list
[19, 25, 43, 33]
I want to do this using a for loop, and as naively as possible, as I usually find that easiest to understand.
I have managed to print all of the keys using a for loop:
for i in d:
print i
for j in d[i]:
print j
but when I tried to edit it to print the values I got the error
NameError: name 'value' is not defined. How can I get 'value' to mean the value attached to a key?
Here is my edited version
for i in d:
print (i[value])
for j in d[i]:
print (j[value])
I am using python 2.7
You can access values in the dict with the help of the method values():
[i['age'] for i in d.values()]
# ['19', '25', '43', '33']
>>> [d.get(k).get('age') for k, v in d.items()]
['33', '25', '19', '43']
In-order to access a dictionary's value you are iterating through keys first which is correct i.e. for i in d:. So, in order to access value of key i in d, you'll need to do d[i] which will give you the value, for example {'name': 'rob', 'age': '33'} then to access the required key you'll have to access from dictionary once more i.e. d[i]['age'].
For some reason my small small brain is having problems with this, I have a list of tuples list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]. Im trying to move these values into a dictionary for parsing later. I have made a few attempts, below the latest of these and im not getting all results into the dict, the dict ends up with the last value iterated (its recreating the dict each time).
people = {}
list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]
for value in list:
people = {'person': [dict(item.split(":",1) for item in value)]}
You can try this one too:
inlist = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]
d = []
for tup in inlist:
tempDict = {}
for elem in tup:
elem = elem.split(":")
tempDict.update({elem[0]:elem[1]})
d.append({'person':tempDict})
print(d)
Output:
[{'person': {'location': 'brazil', 'name': 'john', 'age': '25'}}, {'person': {'location': 'acme', 'name': 'terry', 'age': '32'}}]
If you want a dictionary with a key person and values the dictionaries with the people's info, then replace d.append({'person':tempDict}) with d.append(tempDict) and add d = {'person':d} right before printing.
Output:
{'person': [{'location': 'brazil', 'name': 'john', 'age': '25'}, {'location': 'acme', 'name': 'terry', 'age': '32'}]}
You can try this:
l = [('name:john','age:25','location:brazil'),('person:terry','age:32','location:acme')]
people = [{c:d for c, d in [i.split(':') for i in a]} for a in l]
Output:
[{'name': 'john', 'age': '25', 'location': 'brazil'}, {'person': 'terry', 'age': '32', 'location': 'acme'}]
First of all try not to call your list list. This name is protected in python and used usually to get a list out of iterators or ranges etc.
I would make a list of people first and then append each person to the people list as separate dictionary as follows:
people = []
my_list = [('name:john','age:25','location:brazil'),('person:terry','age:32','location:acme')]
for tup in my_list:
person = {}
for item in tup:
splitted = item.split(':')
person.update({splitted[0]:splitted[1]})
people.append(person)
The output then would be this:
[{'age': '25', 'location': 'brazil', 'name': 'john'},
{'age': '32', 'location': 'acme', 'person': 'terry'}]
I'm trying to figure out how to run 1 list through another list, and whenever the first names match, append it to the new list if it exists
list1 = [["Ryan","10"],["James","40"],["John","30"],["Jake","15"],["Adam","20"]]
list2 = [["Ryan","Canada"],["John","United States"],["Jake","Spain"]]
So it looks something like this.
list3 = [["Ryan","Canada","10"],["John","United States","30"],["Jake","Spain","15"]
So far I haven't really been able to even come close, so even the smallest guidance would be much appreciated. Thanks.
You could transform them into dictionaries and then use a list comprehension:
dic1 = dict(list1)
dic2 = dict(list2)
list3 = [[k,dic2[k],dic1[k]] for k in dic2 if k in dic1]
If ordering isn't a concern, the most straightforward way is to convert the lists into more suitable data structures: dictionaries.
ages = dict(list1)
countries = dict(list2)
That'll make it a cinch to combine the pieces of data:
>>> {name: [ages[name], countries[name]] for name in ages.keys() & countries.keys()}
{'Ryan': ['10', 'Canada'], 'Jake': ['15', 'Spain'], 'John': ['30', 'United States']}
Or even better, use nested dicts:
>>> {name: {'age': ages[name], 'country': countries[name]} for name in ages.keys() & countries.keys()}
{'Ryan': {'country': 'Canada', 'age': '10'},
'Jake': {'country': 'Spain', 'age': '15'},
'John': {'country': 'United States', 'age': '30'}}
If the names are unique you can make list1 into a dictionary and then loop through list2 adding items from this dictionary.
list1 = [["Ryan","10"],["James","40"],["John","30"],["Jake","15"],["Adam","20"]]
list2 = [["Ryan","Canada"],["John","United States"],["Jake","Spain"]]
list1_dict = dict(list1)
output = [item + [list1_dict[item[0]]] for item in list2]
If not, then you need to decide how to deal with cases of duplicate names.
You can use a set and an OrderedDict to combine the common names and keep order:
list1 = [["Ryan","10"],["James","40"],["John","30"],["Jake","15"],["Adam","20"]]
list2 = [["Ryan","Canada"],["John","United States"],["Jake","Spain"]]
from collections import OrderedDict
# get set of names from list2
names = set(name for name,_ in list2)
# create an OrderedDict using name as key and full sublist as value
# filtering out names that are not also in list2
d = OrderedDict((sub[0], sub) for sub in list1 if sub[0] in names)
for name, country in list2:
if name in d:
# add country from each sublist with common name
d[name].append(country)
print(d.values()) # list(d.values()) for python3
[['Ryan', '10', 'Canada'], ['John', '30', 'United States'], ['Jake', '15', 'Spain']]
If list2 always has common names you can remove the if name in d:
I have two lists of dict
listA = [{'id': 'abc', 'key1': '542696d8485b'}]
listB = [{'id': 'abc', 'key1': '542696d8485b'}, {'id': 'def', 'key1': '27348628grn'}]
I want to extract listC = [{'id': 'abc', 'key1': '542696d8485b'}]
i.e I want to find intersection based on 'id' field( based on any one field, assuming common items in list are exactly same ). Suggest me some efficient pythonic way...
How about something like
listA_set = set(item['id'] for item in listA)
listB_set = set(item['id'] for item in listB)
listC_set = listA_set & listB_set
listC = {item:listA[item] for item in listC_set}
Why not use list comprehension:
listA = [{'id': 'abc', 'key1': '542696d8485b'}]
listB = [{'id': 'abc', 'key1': '542696d8485b'}, {'id': 'def', 'key1': '27348628grn'}]
print [i for i in listA for j in listB if i['id']==j['id']]
You could just use a simple filtering
b_ids = set(d["id"] for d in listB)
result = [d for d in listA if d["id"] in b_ids]
assuming that you would like to keep the dictionary from listA when a possibly different dictionary with the same "id" value is in listB.