d1 = {'name': 'Sagar','age': 25}
d2 = {'name': 'Sassdr', 'age':122}
d3 = {'name': 'Saga23weer', 'age':123344}
d4 = {'name': '2133Sagar', 'age':14322}
ch = input("Enter your value: ")
How can I search inputted value from these dictionaries?
and if found value then it returns Found else return not found.
Why are a search value in different dictionary rather than in one??
Try this
merge all dictionary in one
d5 = {**d1, **d2, **d3, **d4}
and then check
if ch in d5 .values():
print "Found"
else:
print "Not Found"
Make a list of dictionaries and search in it:
d1 = {'name': 'Sagar','age': 25}
d2 = {'name': 'Sassdr', 'age':122}
d3 = {'name': 'Saga23weer', 'age':123344}
d4 = {'name': '2133Sagar', 'age':14322}
d = [d1,d2,d3,d4]
def check(ch):
for entry in d:
if entry["name"] == ch:
return("found")
return ("Not found")
while True:
ch = input("Enter your value: ")
if ch == "stop":
break
print(check(ch))
Output:
>>>
Enter your value: Sagar
found
Enter your value: Someone
Not found
Enter your value: 2133Sagar
found
Enter your value: stop
The effect you want is called key swap. This snippet is the implementation:
def keyswap(yourdict):
cache = {}
for i in yourdict.keys():
cache[yourdict[i]] = i
for i in cache.keys():
yourdict[i] = cache[i]
del cache
It keyswaps inplace.
You can use following code
Python2
def IsFound():
list_dict = [d1, d2, d3, d4]
values_list = []
for each in list_dict:
values_list += each.values()
ch = input('enter your value')
if ch in values_list:
return 'Found'
else:
return 'Not Found'
Python3
def IsFound():
dict = {**d1, **d2, **d3, **d4}
ch = input('enter your value')
if ch in dict.values():
return 'Found'
else:
return 'Not Found'
you need to do:
get the values of dict;
search all dicts;
mark result as "Found" if matches.
for step 1:
dict.values()
for step 2:
there's many way to combine all dicts, as everybody gives.
you can pick all values first to set a new list, then search if your input matches like this:
# combine all dicts
d = d1.values() + d2.values() +d3.values() + d4.values()
# judge if matches
if ch in d:
# do something
hope this code can release your confuse.
Related
all the contents must be inserted from the input
graph={
'A':{'B':3,'C':4},
'B':{'A':3,'C':5},
'C':{'B':5,'D':'1'},
'D':{'C':1},
}
Take the input in JSON format and then you can easily use json.loads to convert it to a dictionary.
>>> import json
>>> graph = json.loads(input("Enter graph as JSON: "))
Enter graph as JSON: {"A":{"B":3,"C":4},"B":{"A":3,"C":5},"C":{"B":5,"D":"1"},"D":{"C":1}}
>>> import pprint
>>> pprint.pprint(graph)
{'A': {'B': 3, 'C': 4},
'B': {'A': 3, 'C': 5},
'C': {'B': 5, 'D': '1'},
'D': {'C': 1}}
record_to_insert = int(input("num of record to insert :: "))
dic = {}
for i in range(record_to_insert):
print("")
key_name = input("parent key name :: ")
dic[key_name] = {}
print("Enter how many number of key,value pairs you want for key :: ",
key_name)
num_of_child_keyvalues_to_insert = int(input(""))
for k in range(num_of_child_keyvalues_to_insert):
key = input("child key name :: ")
value = input("Value name :: ")
dic[key_name][key] = value
print(dic)
def make_dict():
d = {}
while True:
key = input("Enter the key of dict or stay blank to finish adding key to this level of dict: ")
if key == "": # just stay blank to out from func
break
ch = input(f"Do you wanna to create nested dict for the key{key}? [y / <Press Enter for No>] ")
if ch == "y":
value = make_dict() # use recursion
else:
value = input(f"Enter the value for the key {key}: ")
d[key] = value
return d
print(make_dict())
link to screenshot
I'm following a tutorial (uploaded oct. 2020) about web scraping and storing the data in a dictionary. Everything works fine except the data in my dictionary starts with the newest entry and ends with the first one.
Should: {title,........, budget}
Is: {budget,........, title}
What could be the resaon for this to happen?
Part of the code:
def get_content_value(row_data):
if row_data.find("li"):
return [li.get_text(" ", strip = True).replace("\xa0", " ") for li in row_data.find_all("li")]
else:
return row_data.get_text(" ", strip = True).replace("\xa0", " ")
movie_info = {}
for index, row in enumerate(info_rows):
if index == 0:
movie_info['title'] = row.find("th").get_text(" ", strip = True)
elif index == 1:
continue
else:
content_key = row.find("th").get_text(" ", strip = True)
content_value = get_content_value(row.find("td"))
movie_info[content_key] = content_value
movie_info
index == 0 is the title
index == 1 is a picture i don't want to have
EDIT:
It's not reversed, it's in alphabetical order! Why? And how can i change it to chronological order?
Dictionaries are inherently not sorted/ordered. This is unlike lists and tuples that are ordered. To get around this issue, the collections library has OrderedDict.
You can use something like this:
# Import the OrderedDict object from `collections`
from collections import OrderedDict
def get_content_value(row_data):
if row_data.find("li"):
return [li.get_text(" ", strip = True).replace("\xa0", " ") for li in row_data.find_all("li")]
else:
return row_data.get_text(" ", strip = True).replace("\xa0", " ")
# Instead of using a regular dictionary ("{}"), we set `movie_info` to be an OrderedDict
movie_info = OrderedDict()
for index, row in enumerate(info_rows):
if index == 0:
movie_info['title'] = row.find("th").get_text(" ", strip = True)
elif index == 1:
continue
else:
content_key = row.find("th").get_text(" ", strip = True)
content_value = get_content_value(row.find("td"))
movie_info[content_key] = content_value
movie_info
It's a bit tricky, but you can do it like below.
from collections import OrderedDict
dictionary = {'one': 1, 'two': 2, 'three':3}
res = OrderedDict(reversed(list(dictionary.items())))
What I want is to reorder this '01110100' by a key 41325768 ,
the expected result: 11100010 , code result:10110010.
def perm(block, key):
block = list(block)
key = list(map(int, str(key))) # converting key to list
key = [x - 1 for x in key] # subtracting 1 from each (zero based)
new_key = [key[i] for i in key]
block = [block[i] for i in new_key]
block = "".join(block)
return block
so I added this line new_key = [key[i] for i in key] to fix the issue but the result so close:11100100
No idea what to do to fix it...😥
The difference between what you want and what you have is the difference in interpretation of the key. For example regarding the "4" at the start of your key, you want that to mean "put the first character in 4th position" but it's being used to say "take the first character from the fourth position".
You can change to the intended action by
def perm(block, key):
new_block = [" "]*len(key)
for ix, kval in enumerate(key):
new_block[int(kval)-1] = block[ix]
return "".join(new_block)
keyc = input('Permutation key: ')
plain = input('String to encode: ')
print ('\nResult: ', perm(str(plain),str(keyc)))
Input/output:
Permutation key: 41325768
String to encode: 01110100
Result: 11100010
I think I understood what means but your approach is wrong, here is a simple version of your code I made.
bi_s = '01110100'
key_s = '41325768'
new_bi = ''
bi_list = list(map(int, str(bi_s)))
key_list = list(map(int, str(key_s)))
print("The New Key")
for i in key_list:
# print(bi_list[i-1], end='', flush=True)
new_bi += str(bi_list[i-1])
print(new_bi)
print("The Origin Key")
for i in bi_list:
print(i, end='', flush=True)
the output :
The New Key
10110010
The Origin Key
01110100
val = dict()
def vote(val,person):
if person not in val:
val[person] = 1
else:
val[person] = val[person] + 1
def votes(val,person):
if person in val:
print val[person]
def result(val):
ex = sorted(val.items(), key = lambda val:val[1], reverse=True)
if len(ex) == 0:
print '***NONE***'
#Problem below
elif ex[0] == ex[1]:
print '***NONE***'
else:
print ex[0][0]
Output:
>>>vote(val,'Peter')
>>>vote(val,'Peter')
>>>votes(val,'Peter')
2
>>>vote(val,'Lisa')
>>>vote(val,'Lisa')
>>>votes(val,'Lisa')
2
>>>result(val)
Lisa
>>> print val
{'Lisa': 2, 'Peter': 2}
I want to try to find if 2 keys have the same values, and if they do I want to print "NONE" if that happens. Obviously it doesn't work since it prints "Lisa" instead, any tips on how to do it?
In your result function need to check the votes in the elif part.
elif ex[0][1] == ex[1][1]:
print ('***NONE***')
I want to ask the user for 2 inputs, first name and last name, return a greeting and store the names in a Dictionary with the Keys being 'FName' and 'LName'
The following stores the greeting fine....
def name():
d = {}
x = input('Please enter your first name: ')
y = input('Please enter your last name: ')
d = {}
d[x] = y
print("Hello", x, y)
print(d)
name()
but I am not sure how to get the key/values in the dictionary properly. Right now it stores the equivalent of:
{'Joe': 'Smith'}
I know I need to reformat the following line different I am just not sure how to approach it...
d[x] = y
You'll want to manually set the keys you are storing against
d['FName'] = x
d['LName'] = y
Or more simply
d = {
'FName': x,
'LName': y
}
Here is another example:
def name():
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
return d
name()
Nevermind, I figured it out. Sorry.
d['Fname'] = x
d['Lname'] = y