Python: Replace a specific word in value of dictionary - python

I have a dictionary
a = {'url' : 'https://www.abcd.com'}
How to use replace and removed 'https://www.' and just be 'abcd.com'?
I tried
a = [w.replace('https://www.', '') for w in a]
But it only return the key. Thanks!

If your dictionary has more entries:
a_new = {k:v.replace('https://www.', '') for k,v in a.items()]

You access the values of the dictionary using: a['url']
and then you update the string value of url using the replace function:
a['url'] = a['url'].replace('https://www.', '')

There is nothing to iterate on, just retrieve the key, modify it, and save it
a = {'url': 'https://www.abcd.com'}
a['url'] = a['url'].replace('https://www.', '')
print(a) # {'url': 'abcd.com'}

The syntax for dict comprehension is slightly different:
a = {key: value.replace('https://www.', '') for key, value in a.items()}
As per documentation: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
And https://docs.python.org/3/tutorial/datastructures.html#looping-techniques for dict.items().

if you want your result to be a dictionary:
a = {k: v.replace('https://www.', '') for k, v in a.items()}
if you want your result to be an array:
a = [v.replace('https://www.', '') for v in a.values()]
More on dictionary comprehension here: https://www.python.org/dev/peps/pep-0274/

Related

Indexing Dictionary in a Dictionary in Python

I have the following problem:
Given a dictionary in dictionary:
dict1={"user1":{"id":"1", "link":"http://..."}, "user2":{"id":"2", "link":"http://..."}, ... }
I need:
params = {"user_ids":["1","2", ... ]}
I tried:
params ={
"user_ids": dict1.values()["id"]
}
but that's not working. It gives an error: 'dict_values' object is not subscriptable.
Is there a way to solve this?
You can use loop. Loop using for loop and each one will be inner dict. Now append all the "ids" in a list. After completion of loop, create a dictionary and print it. Your code:
dict1={"user1":{"id":"1", "link":"http://..."}, "user2":{"id":"2", "link":"http://..."} }
f=[]
for i in dict1:
f.append(dict1[i]["id"])
f1={"user_ids":f}
print(f1)
Edit you dict1 accordingly
Using a list comprehension:
user_ids = [d['id'] for d in dict1.values()]
Or using operator.itemgetter:
from operator import itemgetter
user_ids = list(map(itemgetter('id'), dict1.values()))
If I understand correctly, then the question is that the keys are in the form user + digit, then:
dict1 = {"user1":{"id":"1", "link":"http://..."}, "user2":{"id":"2", "link":"http://..."}}
ids = []
for k, v in dict1.items():
if 'user' in k:
for k, v in v.items():
if k == 'id':
ids.append(v)
params = {'users_id': ids}
print(params)
result: {'users_id': ['1', '2']}

Create a list comprehension from a dictionay

Is it possible to create a list comprehension for the below for loop?
for key, value in some_dict.items():
if my_value in value:
my_new_var = value['sub_item'].split[0]
This will work :
d={'name':'Yash','age':16}
###############################
keys_values = d.items() # Bonus: Converting the dictionary keys and values to string
d = {str(key): str(value) for key, value in keys_values}#--- ''
#########################
my_value='Yash'
my_new_var = [v for k, v in d.items() if my_value in v] [-1] # edit: now it'll take last value
print(my_new_var)
i managed to do something like this:
out = [value['sub_value'].split[0] for key, value in some_dict.items() for i in value if my_new_var in value]

want to find a matching variable from multi key possibly tuples in dict and print the value in python

How can i search a variable from a multi key dict and get the respective value in python?
dict1 = {('1700','2700','3700'):'a3g3',('1502','1518'):'a2g3',('2600'):'a3g2'}
var = '1502'
output
should be a2g3
One way:
dict1 = {('1700','2700','3700'): 'a3g3',
('1502','1518'): 'a2g3',
('2600'): 'a3g2'}
print(next(v for k, v in dict1.items() if '1502' in k))
# a2g3
List comprehension is good approach ,
Here is Filter approach just for fun :
You can filter the result :
dict1 = {('1700','2700','3700'):'a3g3',('1502','1518'):'a2g3',('2600'):'a3g2'}
var = '1502'
print(dict1[list(filter(lambda x:var in x,dict1.keys()))[0]])
output:
a2g3
Just iterate over the keys and find
print([dict1[i] for i in dict1.keys() if var in i])

Python Iterating in a dictionary to get empty key's

Hello guys I'm trying to iterate from a dictionary to get the keys in case some of keys would be empty, but I have no idea how to achieve this.
Any idea ?
def val(**args):
args = args
print args
# print args
# print (args.keys())
val(name = '', country = 'Canada', phone = '')
Whit this example I got {'country': 'Canada', 'name': '', 'phone': ''} but when I'm really looking is to get only the keys of the empty keys in a list using append, the problem is that it gives me all the keys when and not just the empty keys.
In that case I would like to return something like this:
name, phone
I appreciate your help.
Iterate the dictionary and extract keys where the value is an empty string:
empty_keys = [k for k, v in args.items() if v == '']
or as a function:
>>> def val(**args):
... return [k for k, v in args.items() if v == '']
...
>>> val(name = '', country = 'Canada', phone = '')
['phone', 'name']
This is how you get a list of the empty keys:
empty = [k for k, v in args.items() if not v or v.isspace()]
Notice that the above includes the cases when the value is None or '' or only spaces.
The for statement can be used to iterate over the key/values of a dictionary, then you can do what you want with them.
def val(args) :
outputList = []
for k, v in args :
if v == '' :
outputList.append(k)
return outputList
This function will return a list made up of the keys whose value are the empty string.

Removing nested dict items with dict comprehension

I have two dicts:
blocked = {'-5.00': ['121', '381']}
all_odds = {'-5.00': '{"121":[1.85,1.85],"381":[2.18,1.73],"16":[2.18,1.61],"18":\
[2.12,1.79]}'}
I want to first check whether the .keys() comparision (==) returns True, here it does (both -5.00) then I want to remove all items from all_odds that has the key listed in blocked.values() .
For the above it should result in:
all_odds_final = {'-5.00': '{"16":[2.18,1.61],"18": [2.12,1.79]}'}
I tried for loop:
if blocked.keys() == all_odds.keys():
for value in blocked.values():
for v in value:
for val in all_odds.values():
val = eval(val)
if val.has_key(v):
del val[v]
which you know is very ugly plus it's not working properly yet.
First, make the string a dictionary with ast.literal_eval(). Don't use eval():
>>> import ast
>>> all_odds['-5.00'] = ast.literal_eval(all_odds['-5.00'])
Then you can use a dictionary comprehension:
>>> if blocked.keys() == all_odds.keys():
... print {blocked.keys()[0] : {k:v for k, v in all_odds.values()[0].iteritems() if k not in blocked.values()[0]}}
...
{'-5.00': {'18': [2.12, 1.79], '16': [2.18, 1.61]}}
But if you want the value of -5.00 as a string...
>>> {blocked.keys()[0]:str({k: v for k, v in all_odds.values()[0].iteritems() if k not in blocked.values()[0]})}
{'-5.00': "{'18': [2.12, 1.79], '16': [2.18, 1.61]}"}
Here's how you can do the same in about 2 lines. I'm not going to use ast, or eval here, but you can add that if you want to use that.
>>> blocked = {'-5.00': ['121', '381']}
>>> all_odds = {'-5.00': {'121':[1.85,1.85],'381':[2.18,1.73],'16':[2.18,1.61],'18':\
... [2.12,1.79]}}
>>> bkeys = [k for k in all_odds.keys() if k in blocked.keys()]
>>> all_odds_final = {pk: {k:v for k,v in all_odds.get(pk).items() if k not in blocked.get(pk)} for pk in bkeys}
>>> all_odds_final
{'-5.00': {'18': [2.12, 1.79], '16': [2.18, 1.61]}}
This seems to work:
blocked = {'-5.00': ['121', '381']}
all_odds = {'-5.00': {"121":[1.85,1.85],"381":[2.18,1.73],"16":[2.18,1.61],"18":\
[2.12,1.79]}}
all_odds_final = dict(all_odds)
for key, blocks in blocked.iteritems():
map(all_odds_final[key].pop,blocks,[])
If you do not want to copy the dictionary, you can just pop items out of the original all_odds dictionary:
for key, blocks in blocked.iteritems():
map(all_odds[key].pop,blocks,[])
The empty list in the map function is so pop gets called with None as it's second argument. Without it pop only gets one argument and will return an error if the key is not present.

Categories

Resources