Reputation: 323
everyone, recently I am trying to create a list from my data
Here is my data:
!wget --no-check-certificate 'https://drive.google.com/uc?export=download&id=1VfkX_asEXo1HpdSE68Cl_HEdyrKPDxsw' -O /content/API_UAT2.txt
I want to find whether these items exist in my data
tunnel_fares = {
'Aberdeen Tunnel':5
, 'Lion Rock Tunnel':8
, 'Shing Mun Tunnels':5
, 'Tseung Kwan O Tunnel':3
, 'Tsing Sha Highway':8
, 'Cross Harbour Tunnel':20
, 'Eastern Harbour Crossing':40
, 'Western Harbour Crossing':85
, 'Tate\'s Cairn Tunnel':20
, 'Tai Lam Tunnel':48
, 'Lantau Link':30
}
Here is my code
with open ('API_UAT2.txt') as f: #open the txt
js = json.load(f) #turns it to json format
data = js['routes'][0]['legs'][0]['steps']
for item in data:
data_name = item['name']
toll = []
for name,fare in tunnel_fares.items():
if name in data_name:
toll = name
print(toll)
It finally returns
Western Harbour Crossing
Tsing Sha Highway
Tsing Sha Highway
However, I want to turn it into a list, and remove duplicated object i.e.:
['Western Harbour Crossing', 'Tsing Sha Highway']
I tried to use
new = list(map(lambda x:x, toll))
But it turns out a super weird thing. So how can I do this? Thank you very much.
Upvotes: 0
Views: 120
Reputation: 914
Try this:
Code Syntax
with open ('API_UAT2.txt') as f: #open the txt
js = json.load(f) #turns it to json format
data = js['routes'][0]['legs'][0]['steps']
for item in data:
data_name = item['name']
toll = []
for name,fare in tunnel_fares.items():
if name in data_name:
toll.append(name)
toll= list(set(toll))
print(toll)
Output Syntax
['Western Harbour Crossing', 'Tsing Sha Highway']
Upvotes: 1
Reputation: 309
for removing duplicate items from list named l, you can use this code:
l = list(set(l))
Upvotes: 1
Reputation: 32532
You could use a set instead:
with open ('API_UAT2.txt') as f: #open the txt
js = json.load(f) #turns it to json format
data = js['routes'][0]['legs'][0]['steps']
tolls = set()
for item in data:
data_name = item['name']
toll = []
for name, fare in tunnel_fares.items():
if name in data_name:
tolls.add(name)
Upvotes: 1
Reputation: 15478
Append to a list toll
and remove duplicates using dict.fromkeys
:
with open ('API_UAT2.txt') as f: #open the txt
js = json.load(f) #turns it to json format
data = js['routes'][0]['legs'][0]['steps']
for item in data:
data_name = item['name']
toll = []
for name,fare in tunnel_fares.items():
if name in data_name:
toll.append(name)
toll = list(dict.fromkeys(toll))
Upvotes: 1
Reputation: 3383
To add an item to a list you would use:
toll.append(name)
instead of:
toll = name
Therefore your code will be:
with open ('API_UAT2.txt') as f: #open the txt
js = json.load(f) #turns it to json format
data = js['routes'][0]['legs'][0]['steps']
for item in data:
data_name = item['name']
toll = []
for name,fare in tunnel_fares.items():
if name in data_name:
toll.append(name)
print(toll)
Upvotes: 1