I am new to here and asking a question relating to python.
I have a list of city's name, population and area, for example:
city:NewYork population:30 area:1000
city:LosAngles population:3 area:500
.....
but the data is in a list, e.g.
list[0] = 'city:NewYork population:30 area:1000'
list[1] = 'city:LosAngles population:3 area:500'
I would like to convert this list to dictionary list,
the result like to be:
result[0]["city"] =NewYork
result[0]["population"] = 30
I tried many methods, but dont know how to solve it.
Can anyone help me?
thanks in advance!
Split on spaces, then on colons:
result = [dict(item.split(':') for item in value.split()) for value in inputlist]
where inputlist is the original list of strings.
Demo:
>>> inputlist = '''\
... city:NewYork population:30 area:1000
... city:LosAngles population:3 area:500
... '''.splitlines()
>>> [dict(item.split(':') for item in value.split()) for value in inputlist]
[{'city': 'NewYork', 'area': '1000', 'population': '30'}, {'city': 'LosAngles', 'area': '500', 'population': '3'}]
Related
I have two lists of dictionaries and I'd like to find the difference between them (i.e. what exists in the first list but not the second, and what exists in the second list but not the first list).
I want to find the values in the list that are different from each other in terms of location and country. That is, only the list values that differ. That means for example I just want to know, there is no match for Australia
The issue is that it is a list of dictionaries
a = [{'location': 'USA'}, {'location': 'Australia'}]
b = [{'countryID': 1,'country': 'USA'}, {'countryID': 2, 'country': 'UK'}]
With for loops it did not work.
new_list = []
for x in range(len(a)):
for y in range(len(b)):
if a[x]["Location"] != b[y]["country"]:
new_list.append(a[x]["Location"])```
How can I solve the problem?
Use twice comprehensions:
>>> a = [{'location': 'USA'}, {'location': 'Australia'}]
>>> b = [{'countryID': 1,'country': 'USA'}, {'countryID': 2, 'country': 'UK'}]
>>> s = {dct['country'] for dct in b}
>>> [dct for dct in a if dct['location'] not in s]
[{'location': 'Australia'}]
Your for loop is not working because you are checking each pair from the two lists - you can restructure your for loop to only append if not found entirely within the other list
new_list = []
for locn_dict in a:
for country_dict in b:
if locn_dict['location'] == country_dict['country']:
break
else: # This else is with the for, not if
new_list.append(locn_dict['location'])
Output
['Australia']
I have a list with dictionary contained within it in the format:
mydataset =
[{'thing1': 'pink',
'thing2': 'apple',
'thing3': 'car',
'data': [{'firstname': 'jenny',
'lastname': 'jones',
}]},
{'thing1': 'blue',
'thing2': 'banana',
'thing3': 'bicycle',
'data': [{'firstname': 'david',
'lastname': 'walls',
}]}]
I want to be able to extract all the items called firstname within 'data', i.e. 'jenny' and 'david'.
I've tried an approach of myextract = [x in x if mydataset['data']], but of course it fails because I think I'm looking for a value with that. My mental model of the data structure isn't right at the moment.
Try the following:
res = [i['data'][0]['firstname'] for i in mydataset]
output:
['jenny', 'david']
side note: please put banana and apple inside single quotes.
Use the following list comprehension:
res = [di["firstname"]for d in mydataset for di in d["data"] if "firstname" in di]
print(res)
Output
['jenny', 'david']
The above list comprehension is equivalent to the following for-loop:
res = []
for d in mydataset:
for di in d["data"]:
if "firstname" in di:
res.append(di["firstname"])
print(res)
Note that both solutions above will work for more than one element in the sub-dictionary d["data"] and even if the "firstname" key is not present.
For the sake of reusability you could also define a function that will let you access individual values in the dataset and use it for this particular example:
def nested_getitem(path, dic):
from operator import getitem
from functools import reduce
return reduce(getitem, path, dic)
res = [nested_getitem(["data", 0, "firstname"], d) for d in mydataset]
print(res)
Output
['jenny', 'david']
I'm referring to the following code provided by Klaus Byskov Pedersen (How to search if dictionary value contains certain string with Python).
Goal: I want to substitute "Mary" with a list that consists out of 150+ strings. However, When I try to provide a list instead of a "Mary" into the search function I receive this error:
TypeError: 'in <string>' requires string as left operand, not list
Ask: I tried to wrap searchFor in the if statement in [], but received the same error. What am I doing wrong? Ideally, I want the search function to tell me what values in myList are also in myDict.
Code provided below:
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}
def search(values, searchFor):
for k in values:
for v in values[k]:
if searchFor in v:
return k
return None
#Checking if string 'Mary' exists in dictionary value
print search(myDict, 'Mary') #prints firstName
If your using python3 use print(search(myDict, 'Mary')), other than that it works! can you be more specific what is your problem
If you need your function to search multiple items contained in a list then include the last print statement in a for like this,
l1=['Mary','Main','Lee']
for i in l1:
print(search(myDict, i))
code:
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}
def search(values, searchFor):
for k in values:
for v in values[k]:
if searchFor in v:
return k
return None
l1=['Mary','Main','Lee']
for i in l1:
print(search(myDict, i))
output:
firstName
address
lastName
Let me know if I understood it correctly.
The exercise sounds like this:
Write a function that reads a CSVfile. It should return a list of dictionaries,using the first row as key names,and each subsequent rowas values for those keys.For the data in the previous example it would return:
[{'name': 'George', 'address': '4312 Abbey Road', 'age': 22}, {'name': 'John', 'address': '54 Love Ave', 'age': 21}]
Input file(csv):
name,address,age
George,4312 Abbey Road,22
My code is:
with open(filename,'r',newline='') as fin:
reader = csv.reader(fin)
data = list(reader)
# Creating keys for the dict using row[0]
for each in data[0]:
result[each] = 0
for key,value in result.items():
for each_list in data[1:]:
for each_item in each_list:
result[key] = each_item
print(result)
Result:
PS C:\Users\\Desktop> py .\test.py
{'name': '22', 'address': 0, 'age': 0}
{'name': '22', 'address': '22', 'age': 0}
{'name': '22', 'address': '22', 'age': '22'}
And I don't understand why is this happening. Why each_item keeps having only 22 ? It should be George then 4321 Abbey Road and finally 22.
Assuming you have read the file, line-by-line, in a variable called 'lines'.
You could do something like this:
[{tpl[0]:tpl[1] for tpl in zip(lines[0].split(','), line.split(','))} for line in lines[1:]]
What this does:
The outer-most function creates an array.
Its syntax is [a for b in c]
Meaning: create an array of items a, where each item a can be calculated from a value b, which is part of an iterable c
We are using that function to create an array of dictionaries.
The function one level deeper is {k:v for y in z}
Meaning: construct a dictionary with key k and value v, whose values can be calculates from y, which is part of an iterable z
And finally, the zip function. Which takes two iterables, and returns an iterable of their tuples.
So, from the bottom:
take line 0 of the lines you've read (which is the header)
zip line 0 together with every line in turn, creating an iterable of tuples
for every line, go over this iterable of tuples, and convert it to a dictionary
add all those dictionaries to one array
Consider myself a beginner with Python. I'm trying to do something I've not quite done before and am completely stumping myself.
Hoping someone can give me a clue as which path to take on this.
I have a number of lists within a larger list.
I would like to iterate through the large list and modify data in each sub-list. There are a number of common variables within each list, but not all lists will be the same.
Example:
LIST = [
['Name: Dave', 'Age 28', 'Dogs', 'Football',],
['Name: Tony', 'Age 22', 'Beer', 'Star Wars', 'Hotdogs']
]
The end goal is to have 1 large list with each sublist converted to a dictionary.
Goal:
LIST = [
{'Dave' : { 'Age' : '28' } {'Likes' : ['Dogs', 'Football']}},
{'Tony' : { 'Age' : '22' } {'Likes' : ['Beer', 'Star Wars', 'Hotdogs']}}
]
The conversion to dictionary I will worry about later. But I am struggling to get my head around working with each sub-list in a loop.
Any ideas would be highly appreciated.
Thanks!
list2 = []
for el in list1:
list2.append( compute(el))
where compute is a method that will turn your list into the dictionary you want
result = {}
temp = {}
for x in LIST:
key = x[0][6:]
key_1 = x[1][:3]
value_1 = x[1][3:]
key_2 = 'Likes'
value_2 = x[2:]
temp[key_1] = value_1
temp[key_2] = value_2
result[key] = temp
temp = {}
Try this
but as you know dictionary has no sequence , no guarantee for age to be second in dictionary
Here's an answer to get your dictionary in both the ways mentioned by Tom Ellis.
LIST = [
['Name: Dave', 'Age 28', 'Dogs', 'Football', ],
['Name: Tony', 'Age 22', 'Beer', 'Star Wars', 'Hotdogs']
]
l = list()
for li in LIST:
d = dict()
likes_list = []
for i in li:
if "name" in i.lower():
d.update(dict([i.replace(' ', '').split(":")])) #removing the whitespace for formatting.
elif "age" in i.lower():
d.update(dict([i.split()]))
else:
likes_list.append(i)
d["likes"] = likes_list
l.append(d)
print l
Which results in:
>>> [{'Age': '28', 'Name': 'Dave', 'likes': ['Dogs', 'Football']}, {'Age': '22', 'Name': 'Tony', 'likes': ['Beer', 'Star Wars', 'Hotdogs']}]
If you really want the dictionary in the format you stated first, you could continue with the program like this:
l2 = []
for element in l:
nd = {}
name = element.pop("Name").strip()
nd[name] = element
# print nd
l2.append(nd)
print l2
Which results in the way you stated:
>>> [{'Dave': {'Age': '28', 'likes': ['Dogs', 'Football']}}, {'Tony': {'Age': '22', 'likes': ['Beer', 'Star Wars', 'Hotdogs']}}]
Axnyff's answer is pretty much what you want
ShadowRanger's comment on Axnyff's answer is definitely what you want. List comprehensions are really cool!
Simply iterating over the list with a for loop lets you work on each sub-list and do whatever you want to it.
It looks like you don't really want to modify the lists in place, rather you want to process each list into a dictionary (and extracting that process into a separate function is very good for readability), and put those new dictionaries into a new list.
EDIT:
Also, as correctly mentioned in a down-voted answer, your dictionaries should probably be in the form:
{'Name': 'Dave', 'Age': 28, 'Likes': ['Dogs', 'Football']}
Unless you actually want to use the dictionary to find their information by their name, in which case this is the correct syntax:
{'Dave' : { 'Age' : 28, 'Likes' : ['Dogs', 'Football']}}
LIST=[{'Name': 'Dave', 'Age': 28, 'likes':['Dogs', 'Football']},{'Name': 'Tony', 'Age': 22, 'likes':['Beer', 'Star Wars', 'Hotdogs']}]
You Do like This, Thank You.