How to get complete dictionary data inside lists. but first I need to check them if key and value is exists and paired.
test = [{'a': 'hello' , 'b': 'world', 'c': 1},
{'a': 'crawler', 'b': 'space', 'c': 5},
{'a': 'jhon' , 'b': 'doe' , 'c': 8}]
when I try to make it conditional like this
if any((d['c'] is 8) for d in test):
the value is True or False, But I want the result be an dictionary like
{'a': 'jhon', 'b': 'doe', 'c': 8}
same as if I do
if any((d['a'] is 'crawler') for d in test):
the results is:
{'a': 'crawler', 'b': 'space', 'c': 5}
Thanks in advance
is tests for identity, not for equality which means it compares the memory address not the values those variables are storing. So it is very likely it might return False for same values. You should use == instead to check for equality.
As for your question, you can use filter or list comprehensions over any:
>>> [dct for dct in data if dct["a"] == "crawler"]
>>> filter(lambda dct: dct["a"] == "crawler", data)
The result is a list containing the matched dictionaries. You can get the [0]th element if you think it contains only one item.
Use comprehension:
data = [{'a': 'hello' , 'b': 'world', 'c': 1},
{'a': 'crawler', 'b': 'space', 'c': 5},
{'a': 'jhon' , 'b': 'doe' , 'c': 8}]
print([d for d in data if d["c"] == 8])
# [{'c': 8, 'a': 'jhon', 'b': 'doe'}]
Related
a = {'a': 1, 'b': [{'a1': 1,'b2': 2}], 'c': 3, 'd': 4, 'e': 5}
b = {'c': 3, 'b': [{'a1': 1,'b2': 2}]}
Check for the presence of b in a, and the output is a bool value
Tried solutions like this:
for values in b.items():
if values in a.items():
continue
else:
return False
return True
len(set(b.items()) & set(a.items())) == len(b)
The problem is with a value-pair of a key-value whose value-pair is a dictionary. I am looking for a solution to this problem.
maybe this works for you?
a = {'a': 1, 'b': [{'a1': 1,'b2': 2}], 'c': 3, 'd': 4, 'e': 5}
b = {'c': 3, 'b': [{'a1': 1,'b2': 2}]}
c = {'a1': 1,'b2': 3}
def issubset(a,b):
for keyb,valueb in b.items():
if keyb in a and a[keyb] == valueb: continue
return False
return True
print( issubset(a,b) )
print( issubset(a,c) )
print( issubset(a,{'a':'2'}) )
output:
True
False
False
it works for your example. However, as you see in the 2nd line, it doesn't do recursive checking, which might be what you want.
I have a dictionary:
oldDict = {'a': 'apple', 'b': 'boy', 'c': 'cat'}
I want a new dictionary with one of the values in the old dictionary as new key and all the elements as values:
newDict = {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}}
I tried doing this:
newDict['apple'] = oldDict
This does not seem to be working. Please note that I don't have a variable newDict in my script. I just have oldDict and I need to modify the same to make this change in every loop. In the end I will have one dictionary, which will look like this.
oldDict = {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}, 'dog': {'d': 'dog', 'e': 'egg'}}
You need to duplicate your dictionary so you won't create a circular reference.
>>> newDict = {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}}
>>> newDict['potato'] = dict(newDict)
>>> newDict
{'apple': {'a': 'apple', 'c': 'cat', 'b': 'boy'}, 'potato': {'apple': {'a': 'apple', 'c': 'cat', 'b': 'boy'}}}
you need to first create/declare the dictionary before you can added items into it
oldDict = {'a': 'apple', 'b': 'boy', 'c': 'cat'}
newDict = {}
newDict['apple'] = oldDict
# {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}}
# you can 1st create the newDict outside the loop then update it inside the loop
>>> newDict = {}
>>> dict1 = {'a': 'apple', 'b': 'boy', 'c': 'cat'}
>>> dict2 = {'d': 'dog', 'e': 'egg'}
>>> newDict['apple'] = dict1
>>> newDict['dog'] = dict2
>>> newDict
>>> {'apple': {'a': 'apple', 'b': 'boy', 'c': 'cat'}, 'dog': {'d': 'dog', 'e': 'egg'}}
or you could do as below
newDict = {'apple':oldDict}
I can print variables in python.
for h in jl1["results"]["attributes-list"]["volume-attributes"]:
state = str(h["volume-state-attributes"]["state"])
if aggr in h["volume-id-attributes"]["containing-aggregate-name"]:
if state == "online":
print(h["volume-id-attributes"]["owning-vserver-name"]),
print(' '),
print(h["volume-id-attributes"]["name"]),
print(' '),
print(h["volume-id-attributes"]["containing-aggregate-name"]),
print(' '),
print(h["volume-space-attributes"]["size-used"]
These print function returns for example 100 lines. Now I want to print only top 5 values based on filter of "size-used".
I am trying to take these values in dictionary and filter out top five values for "size-used" but not sure how to take them in dictionary.
Some thing like this
{'vserver': (u'rcdn9-c01-sm-prod',), 'usize': u'389120', 'vname': (u'nprd_root_m01',), 'aggr': (u'aggr1_n01',)}
Any other options like namedtuples is also appreciated.
Thanks
To get a list of dictionaries sorted by a certain key, use sorted. Say I have a list of dictionaries with a and b keys and want to sort them by the value of the b element:
my_dict_list = [{'a': 3, 'b': 1}, {'a': 1, 'b': 4}, {'a': 4, 'b': 4},
{'a': 2, 'b': 7}, {'a': 2, 'b': 4.3}, {'a': 2, 'b': 9}, ]
my_sorted_dict_list = sorted(my_dict_list, key=lambda element: element['b'], reverse=True)
# Reverse is set to True because by default it sorts from smallest to biggest; we want to reverse that
# Limit to five results
biggest_five_dicts = my_sorted_dict_list[:5]
print(biggest_five_dicts) # [{'a': 2, 'b': 9}, {'a': 2, 'b': 7}, {'a': 2, 'b': 4.3}, {'a': 1, 'b': 4}, {'a': 4, 'b': 4}]
heapq.nlargest is the obvious way to go here:
import heapq
interesting_dicts = ... filter to keep only the dicts you care about (e.g. online dicts) ...
for large in heapq.nlargest(5, interesting_dicts,
key=lambda d: d["volume-space-attributes"]["size-used"]):
print(...)
I need to write a program that counts the number of values in a dictionary.
For example, say I have this dictionary.
{'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
I should get 6 as a result, because there's 6 values.
When I use this code, I get 4.
def how_many(aDict):
sum = len(aDict.values())
return sum
animals = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
print(how_many(animals))
I'm very new to Python so please don't do anything to hard.
You need to sum the lengths of each of the elements in aDict.values():
>>> aDict = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
>>> sum(len(item) for item in aDict.values())
6
You may use sum on the generator expression to calculate len of each value as:
>>> my_dict = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
# returns list of all values v
>>> sum(len(v) for v in my_dict.values())
6
Alternatively, you may also use map with sum to achieve this as:
>>> sum(map(len, my_dict.values()))
6
I was writing a Python Code that creates dictionaries dynamically,initializes it to a reference dictionary, and modifying a particular value in the dictionary. But,I found that not only I am getting unexpected results,but the reference dictionary is also getting modified.
My Code:
tdict={'a':'1','b':'2','c':'3'}
newdict={}
for i in range(5):
newdict['name'+str(i)]=tdict
newdict['name'+str(i)]['a']='value'+str(i)
print 'tdict: ',tdict
print 'newdict: ',newdict
And the result:
tdict: {'a': 'value0', 'c': '3', 'b': '2'}
tdict: {'a': 'value1', 'c': '3', 'b': '2'}
tdict: {'a': 'value2', 'c': '3', 'b': '2'}
tdict: {'a': 'value3', 'c': '3', 'b': '2'}
tdict: {'a': 'value4', 'c': '3', 'b': '2'}
newdict: {'name4': {'a': 'value4', 'c': '3', 'b': '2'}, 'name2': {'a': 'value4', 'c': '3', 'b': '2'}, 'name3': {'a': 'value4', 'c': '3', 'b': '2'}, 'name0': {'a': 'value4', 'c': '3', 'b': '2'}, 'name1': {'a': 'value4', 'c': '3', 'b': '2'}}
whereas I expected my 'newdict' to be like:
newdict: {'name4': {'a': 'value4', 'c': '3', 'b': '2'}, 'name2': {'a': 'value2', 'c': '3', 'b': '2'}, 'name3': {'a': 'value3', 'c': '3', 'b': '2'}, 'name0': {'a': 'value0', 'c': '3', 'b': '2'}, 'name1': {'a': 'value1', 'c': '3', 'b': '2'}}
Can anyone please help me figuring out why this is happening? Also, why is the reference dictionary 'tdict' getting changed when I am not assigning any any value to it?
Thanks in advance
You are storing a reference to tdict in every value of your newdict dictionary:
newdict['name'+str(i)]=tdict
You are then modifying the key 'a' of tdict by doing
# newdict['name'+str(i)] is a reference to tdict
newdict['name'+str(i)]['a']='value'+str(i)
# this is equivalent to doing
tdict['a']='value'+str(i)
What you maybe want is storing a copy of tdict in your newdict dictionary:
newdict['name'+str(i)]=dict(tdict)
Creating a new dictionary by using an existing dictionary as constructor argument creates a shallow copy where you can assign new values to existing keys. What you cannot (or what you don't want) is modifying mutable values in this dictionary. Example:
>>> a={'a': 1, 'b': 2, 'c': [1,2,3]}
>>> b=dict(a)
>>> b['a']=9
>>> a
{'a': 1, 'c': [1, 2, 3], 'b': 2}
>>> b
{'a': 9, 'c': [1, 2, 3], 'b': 2}
>>> b['c'].append(99)
>>> a
{'a': 1, 'c': [1, 2, 3, 99], 'b': 2}
>>> b
{'a': 9, 'c': [1, 2, 3, 99], 'b': 2}
If you want to modify mutable values in a dictionary you need to create a deep copy:
>>> import copy
>>> a={'a': 1, 'b': 2, 'c': [1,2,3]}
>>> b=copy.deepcopy(a)
>>> b['a']=9
>>> b['c'].append(99)
>>> a
{'a': 1, 'c': [1, 2, 3], 'b': 2}
>>> b
{'a': 9, 'c': [1, 2, 3, 99], 'b': 2}
Is just cause you are making a reference to tdict and not a copy. In order to copy you can either use
newdict['name'+str(i)] = tdict.copy()
or
newdict['name'+str(i)] = dict(tdict)
Hope it helps