Как отфильтровать словарь значением?

Используйте мой инструмент git_remote_branch (Вам нужен Ruby, установленный на Вашей машине). Это создается конкретно для создания удаленных манипуляций ответвлением очень легкими.

Каждый раз, когда это делает операцию от Вашего имени, это печатает его в красном в консоли. Со временем они наконец вонзаются в Ваш мозг:-)

, Если Вы не хотите grb к командам выполнения от Вашего имени, просто используйте 'объяснить' функцию. Команды будут распечатаны к Вашей консоли вместо выполняемого для Вас.

Наконец, все команды имеют псевдонимы, для создания запоминания легче.

Примечание, что это альфа-версия программного обеспечения ;-)

Вот справка при выполнении справки grb:

git_remote_branch version 0.2.6

  Usage:

  grb create branch_name [origin_server] 

  grb publish branch_name [origin_server] 

  grb rename branch_name [origin_server] 

  grb delete branch_name [origin_server] 

  grb track branch_name [origin_server] 



  Notes:
  - If origin_server is not specified, the name 'origin' is assumed 
    (git's default)
  - The rename functionality renames the current branch

  The explain meta-command: you can also prepend any command with the 
keyword 'explain'. Instead of executing the command, git_remote_branch 
will simply output the list of commands you need to run to accomplish 
that goal.

  Example: 
    grb explain create
    grb explain create my_branch github

  All commands also have aliases:
  create: create, new
  delete: delete, destroy, kill, remove, rm
  publish: publish, remotize
  rename: rename, rn, mv, move
  track: track, follow, grab, fetch

5
задан SilentGhost 6 August 2009 в 21:01
поделиться

5 ответов

Приведенный ниже код приведет к двум переменным: соответствует и остаткам . match - это массив словарей, в котором совпадающие элементы из исходного словаря будут иметь соответствующий элемент. остаток будет содержать, как в вашем примере, словарь, содержащий все несовпадающие элементы.

Обратите внимание, что в вашем примере есть только один набор совпадающих значений: ('first / dir' , 'hello.txt') . Если бы было несколько наборов, для каждого была бы соответствующая запись в соответствует .

import itertools

# Original dict
a = {"2323232838": ("first/dir", "hello.txt"),
     "2323221383": ("second/dir", "foo.txt"),
     "3434221": ("first/dir", "hello.txt"),
     "32232334": ("first/dir", "hello.txt"),
     "324234324": ("third/dir", "dog.txt")}

# Convert dict to sorted list of items
a = sorted(a.items(), key=lambda x:x[1])

# Group by value of tuple
groups = itertools.groupby(a, key=lambda x:x[1])

# Pull out matching groups of items, and combine items   
# with no matches back into a single dictionary
remainder = []
matched   = []

for key, group in groups:
   group = list(group)
   if len(group) == 1:
      remainder.append( group[0] )
   else:
      matched.append( dict(group) )
else:
   remainder = dict(remainder)

Вывод:

>>> matched
[
  {
    '3434221':    ('first/dir', 'hello.txt'), 
    '2323232838': ('first/dir', 'hello.txt'), 
    '32232334':   ('first/dir', 'hello.txt')
  }
]

>>> remainder
{
  '2323221383': ('second/dir', 'foo.txt'), 
  '324234324':  ('third/dir', 'dog.txt')
}

Как новичок, вы, вероятно, познакомитесь с несколькими незнакомыми концепциями в приведенном выше коде . Вот несколько ссылок:

10
ответ дан 18 December 2019 в 10:47
поделиться

То, что вы просите, называется «инвертированным индексом» - отдельные элементы записываются только один раз со списком ключей.

>>> from collections import defaultdict
>>> a = {"2323232838": ("first/dir", "hello.txt"),
...      "2323221383": ("second/dir", "foo.txt"),
...      "3434221": ("first/dir", "hello.txt"),
...      "32232334": ("first/dir", "hello.txt"),
...      "324234324": ("third/dir", "dog.txt")}
>>> invert = defaultdict( list )
>>> for key, value in a.items():
...     invert[value].append( key )
... 
>>> invert
defaultdict(<type 'list'>, {('first/dir', 'hello.txt'): ['3434221', '2323232838', '32232334'], ('second/dir', 'foo.txt'): ['2323221383'], ('third/dir', 'dog.txt'): ['324234324']})

Инвертированный словарь имеет исходные значения, связанные с список из 1 или более ключей.

Теперь, чтобы получить ваши исправленные словари из этого.

Фильтрация:

>>> [ invert[multi] for multi in invert if len(invert[multi]) > 1 ]
[['3434221', '2323232838', '32232334']]
>>> [ invert[uni] for uni in invert if len(invert[uni]) == 1 ]
[['2323221383'], ['324234324']]

Расширение

>>> [ (i,multi) for multi in invert if len(invert[multi]) > 1 for i in invert[multi] ]
[('3434221', ('first/dir', 'hello.txt')), ('2323232838', ('first/dir', 'hello.txt')), ('32232334', ('first/dir', 'hello.txt'))]
>>> dict( (i,multi) for multi in invert if len(invert[multi]) > 1 for i in invert[multi] )
{'3434221': ('first/dir', 'hello.txt'), '2323232838': ('first/dir', 'hello.txt'), '32232334': ('first/dir', 'hello.txt')}

Аналогичная (но более простая) обработка работает для элементов, встречающихся один раз.

4
ответ дан 18 December 2019 в 10:47
поделиться

Я предполагаю, что ваш уникальный идентификатор будет ключом.
Возможно, не очень красиво, но возвращает dict с вашими уникальными значениями:

>>> dict_ = {'1': ['first/dir', 'hello.txt'],
'3': ['first/dir', 'foo.txt'], 
'2': ['second/dir', 'foo.txt'], 
'4': ['second/dir', 'foo.txt']}  
>>> dict((v[0]+v[1],k) for k,v in dict_.iteritems())  
{'second/dir/foo.txt': '4', 'first/dir/hello.txt': '1', 'first/dir/foo.txt': '3'}  

Я видел, как вы обновили свое сообщение:

>>> a
{'324234324': ('third/dir', 'dog.txt'), 
'2323221383': ('second/dir', 'foo.txt'), 
'3434221': ('first/dir', 'hello.txt'), 
'2323232838': ('first/dir', 'hello.txt'), 
'32232334': ('first/dir', 'hello.txt')}
>>> dict((v[0]+"/"+v[1],k) for k,v in a.iteritems())
{'second/dir/foo.txt': '2323221383', 
'first/dir/hello.txt': '32232334', 
'third/dir/dog.txt': '324234324'}
1
ответ дан 18 December 2019 в 10:47
поделиться

Итерация по словарю ничем не отличается от итерации по списку в python:

for key in dic:
    print("dic[%s] = %s" % (key, dic[key]))

Это напечатает все ключи и значения вашего словаря.

1
ответ дан 18 December 2019 в 10:47
поделиться

если вы знаете, какое значение вы хотите отфильтровать:

known_tuple = 'first/dir','hello.txt'
b = {k:v for k, v in a.items() if v == known_tuple}

, тогда a станет:

a = dict(a.items() - b.items())

this is py3k, но я уверен, что что-то подобное можно реализовать в устаревших версиях. Если вы не знаете, что такое known_tuple , вам нужно сначала узнать его. например так:

c = list(a.values())
for i in set(c):
    c.remove(i)
known_tuple = c[0]
0
ответ дан 18 December 2019 в 10:47
поделиться
Другие вопросы по тегам:

Похожие вопросы: